Добавить в избранное функция?

#iphone #ios #uitableview #uinavigationcontroller

#iPhone #iOS #uitableview #uinavigationcontroller

Вопрос:

У меня возникла проблема с пониманием того, как сохранять данные, чтобы в моем приложении была функция «добавить в избранное». Приложение имеет UITableView, а данные хранятся в Plist. Оттуда он переходит в DetailView, содержащий UIImageView и UITextView. Я хочу иметь возможность добавлять понравившиеся элементы в закладки и отображать их в отдельном представлении.

Вот фрагмент кода, чтобы его было легче увидеть:

 //BooksLibraryDao.h

#import <Foundation/Foundation.h>


@interface BooksLibraryDao : NSObject {
    NSString *libraryPlist;
    NSArray *libraryContent;
}

@property (nonatomic, readonly) NSString *libraryPlist;
@property (nonatomic, readonly) NSArray *libraryContent;

- (id)initWithLibraryName:(NSString *)libraryName;
- (NSDictionary *)libraryItemAtIndex:(int)index;
- (int)libraryCount;

@end


//BooksLibraryDao.m

#import "BooksLibraryDao.h"


@implementation BooksLibraryDao

@synthesize libraryContent, libraryPlist;

 - (id)initWithLibraryName:(NSString *)libraryName {
    if (self = [super init]) {
        libraryPlist = libraryName;
        libraryContent = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] 
                                                                  pathForResource:libraryPlist ofType:@"plist"]];
    }
    return self;
}

- (NSDictionary *)libraryItemAtIndex:(int)index {
    return (libraryContent != nil amp;amp; [libraryContent count] > 0 amp;amp; index < [libraryContent count]) 
        ? [libraryContent objectAtIndex:index]
        : nil;
}

- (int)libraryCount {
    return (libraryContent != nil) ? [libraryContent count] : 0;
}

- (void) dealloc {
    if (libraryContent) [libraryContent release];
    [super dealloc];
}


@end


//BooksTableViewController.h

#import <UIKit/UIKit.h>
#import "BooksLibraryDao.h"
#import "BooksListingViewCell.h"
#import "BooksAppDelegate.h"


@interface BooksTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
    IBOutlet UITableView *booksTableView;
    BooksLibraryDao *dao;

    IBOutlet BooksListingViewCell *_cell;
}


@end



//BooksTableViewController.m

#import "BooksTableViewController.h"
#import "DetailViewController.h"
#import "BooksListingViewCell.h"
#import "BooksNavController.h"

@implementation BooksTableViewController
#define CELL_HEIGHT 70.0

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor clearColor];
}


- (void)viewWillAppear:(BOOL)animated {
    dao = [[BooksLibraryDao alloc] initWithLibraryName:@"TestData"];
    self.title = @"Books";
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [dao libraryCount];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"LibraryListingCell";

    BooksListingViewCell *cell = (BooksListingViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"BooksListingView" owner:self options:nil];
        cell = [_cell autorelease];
        _cell = nil;
    }

    cell.titleLabel.text = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"];     
    cell.smallImageView.image = [UIImage imageNamed:[[dao libraryItemAtIndex:indexPath.row] valueForKey:@"smallImage"]];    
    cell.backgroundColor = [UIColor colorWithRed:9 green:9 blue:9 alpha:.7];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor colorWithRed:.1 green:.1 blue:.1 alpha:1];
    cell.selectedBackgroundView = [[[UIImageView alloc] init] autorelease];
    UIImage *selectionBackground;
    selectionBackground = [UIImage imageNamed:@"cell.png"];
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *controller = [[DetailViewController alloc] 
                                        initWithBookData:[dao libraryItemAtIndex:indexPath.row]
                                        nibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
    controller.title = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];  

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CELL_HEIGHT;
}


#pragma mark -
#pragma mark Table view delegate


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end


//DetailViewController.h


#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#import <QuartzCore/QuartzCore.h>


@interface DetailViewController : UIViewController <MFMailComposeViewControllerDelegate>{
    IBOutlet UIImageView *bookImageView;
    IBOutlet UILabel *titleLabel;

    IBOutlet UITextView *authorTextView;
    IBOutlet UITextView *descriptionTextView;
    IBOutlet UILabel *message;

    NSDictionary *bookData;
}

@property (nonatomic, retain) UIImageView *bookImageView;
@property (nonatomic, retain) UILabel *titleLabel;

@property (nonatomic, retain) UITextView *descriptionTextView;
@property (nonatomic, retain) UITextView *authorTextView;
@property (nonatomic, retain) IBOutlet UILabel *message;


-(IBAction)showPicker:(id)sender;
-(void)displayComposerSheet;
-(void)launchMailAppOnDevice;
-(IBAction)showAuthor;
-(IBAction)showDesc;
-(IBAction)showImage;

- (id)initWithBookData:(NSDictionary *)data nibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;

@end



//DetailViewController.m

#import "DetailViewController.h"



@implementation DetailViewController

@synthesize bookImageView, titleLabel, descriptionTextView, authorTextView;
@synthesize message;

- (id)initWithBookData:(NSDictionary *)data nibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        bookData = data;
    }
    return self;
}

- (void)viewDidLoad {
    bookImageView.image = [UIImage imageNamed:[bookData valueForKey:@"bookImage"]];
    titleLabel.text = [bookData valueForKey:@"title"];
    descriptionTextView.text = [bookData valueForKey:@"description"];
    authorTextView.text = [bookData valueForKey:@"author"];
    [super viewDidLoad];
}
  

Комментарии:

1. Добро пожаловать в SO! Пара советов по размещению вопроса, на который люди могут ответить. Это действительно помогает конкретизировать ваш вопрос, и вы хотите, чтобы людям было легко увидеть проблему и ответить. В данном конкретном случае это просто слишком много кода, чтобы люди могли разобраться, и вам не было ясно, что вы пробовали и почему это не удалось. Сократите его до основной части вопроса, и вы получите гораздо лучшие ответы.

2. Вы просите пользователей StackOverflow добавить функцию в ваше приложение и написать ваш код для вас. Пожалуйста, ознакомьтесь с рекомендациями о том, как задать вопрос, особенно с разделами «Сделай домашнее задание» и «Задавай вопросы другим пользователям».

3. Извините, если так получилось, я просто просил несколько советов.

Ответ №1:

У вас есть один из нескольких вариантов реализации избранного (на самом деле это зависит в основном от того, являются ли ваши данные постоянными).

  • (A) Вы можете добавить маркер для каждого элемента, отображаемого в вашей таблице, который помечает его как избранный, а затем просто обратитесь к тому же набору данных, но отфильтруйте его по указанному маркеру. Или…

  • (B) Вы можете создать дополнительный список, содержащий копию каждого элемента, который вы хотите пометить как избранный, а затем ссылаться на этот новый список в качестве источника данных.

Если ваши данные не являются постоянными, вы все равно можете использовать метод A и при обновлении данных сохранять только отмеченные записи, прежде чем вставлять новые, свежие данные.

Надеюсь, это имеет смысл!

Комментарии:

1. Спасибо, это немного облегчает понимание того, что я должен делать. Я попробую и посмотрю, что я могу сделать 🙂