2013-02-19 126 views
1

我試圖保存一個對象數組到pList當主頁按鈕或程序退出時,但沒有任何事情發生,該文件似乎永遠不會被創建。將對象的NSMutableArray保存到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
NSDocumentationDirectory 

嗯。我確定你的意思是

NSDocumentDirectory 

改爲。