使用NSCoder保存一组自定义对象,然后从保存的数据中加载UITableView

时间:2013-02-21 18:27:25

标签: xcode uitableview nscoding

当我退出主页按钮或程序时,我正在尝试使用NSCoding保存一组对象,但似乎没有任何事情发生。

我做错了什么????

// Fieldbook.h自定义对象

@interface FieldBook : NSObject <NSCoding>
{
    NSString *title;
    NSDate *date;
}

@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSDate *date;

-(id) init:(NSString *)aTitle;
- (NSString *) description;

@end

// Fieldbook.m

#import "FieldBook.h"
@implementation FieldBook
@synthesize title, date;


-(id) init:(NSString *)aTitle
{
    title = aTitle;
    return  self;
}

- (NSString *) description
{
    NSString *desc = [NSString stringWithFormat:@"%@\n", title];
    return desc;
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init])
    {
        self.title = [decoder decodeObjectForKey:@"title"];
        self.date = [decoder decodeObjectForKey:@"date"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:title forKey:@"time"];
    [encoder encodeObject:date forKey:@"date"];
}

@end

// ViewController.h

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSMutableArray *fieldBooks;
@property (nonatomic, retain) UITextField *projectName;

- (NSString *)dataFilePath;

@end

// ViewController.m

#import "FieldBook.h"
#import "ViewController.h"
@implementation ViewController
@synthesize myTableView, fieldBooks, projectName;

- (void)viewDidLoad
{
    // Do any additional setup after loading the view, typically from a nib.
    [super viewDidLoad];

    if(fieldBooks == nil)
        fieldBooks = [[NSMutableArray alloc]init];

    NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
    [self.fieldBooks addObjectsFromArray:tempArray];

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:app];

    [self.myTableView reloadData];

    //Set title
    self.title = @"FieldBooks";

    //Add edit button
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    //Add the add button
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                               target:self
                                                                               action:@selector(insertNewObject)];

    self.navigationItem.rightBarButtonItem = addButton;

}

- (void)applicationWillResignActive:(NSNotification *)notification
{
    [NSKeyedArchiver archiveRootObject:self.fieldBooks toFile:[self dataFilePath]];
}


- (NSString *)dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    return [documentsDirectory stringByAppendingPathComponent:@"datafile"];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [myTableView setEditing:editing animated:animated];
}

- (void)insertNewObject
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Enter name"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"Cancel"
                                           otherButtonTitles:@"OK", nil];

    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    projectName = [alert textFieldAtIndex:0];

    [alert show];
}

#pragma mark - UIAlertView delegate method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //Only perform if OK button is pressed
    if (buttonIndex == 1)
    {        
        FieldBook *fb = [[FieldBook alloc] init:(NSString *)projectName.text];
        [fieldBooks addObject:fb];

        [myTableView reloadData];

        NSLog(@"FieldBook created: %@", fb);
    }
}


#pragma mark - UITableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    FieldBook *fbName = [self.fieldBooks objectAtIndex:[indexPath row]];
    cell.textLabel.text = fbName.title;

    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //remove from NSMutable array
        [fieldBooks removeObjectAtIndex:indexPath.row];

        //remove from table view
        [myTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

@end

0 个答案:

没有答案