将对象的NSMutableArray保存到pList

时间:2013-02-19 15:53:28

标签: iphone nsmutablearray plist

当我退出主页按钮或程序时,我正在尝试将对象数组保存到pList,但没有任何反应,似乎永远不会创建该文件。

我做错了什么????

// ViewController.h

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

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

- (NSString *)pathOfFile;
- (void)applicationWillTerminate:(NSNotification *)notification;

@end

// ViewController.m

#import "ViewController.h"

@interface ViewController ()
- (void)viewDidLoad
{
    NSString *filePath = [self pathOfFile];
    if ([[NSFileManager defaultManager]fileExistsAtPath:filePath])
    {
        NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
        fieldBooks = [array objectAtIndex:0];
    }

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

    [super viewDidLoad];

    //Instantiate our NSMutableArray

    //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)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;
    [alert show];
}

- (NSString *)pathOfFile
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *documentsFolder = [paths objectAtIndex:0];

    return [documentsFolder stringByAppendingFormat:@"myFile.plist"];
}


- (void)applicationWillTerminate:(NSNotification *)notification
{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    [array addObject:fieldBooks];
    [array writeToFile:[self pathOfFile] atomically:YES];
}

1 个答案:

答案 0 :(得分:1)

NSDocumentationDirectory

嗯。我相信你的意思

NSDocumentDirectory

代替。