存档数据,然后将其加载到viewdidload上

时间:2014-03-20 16:05:52

标签: ios objective-c nsfilemanager

我遵循Objective-C教程,在此任务中,我必须制作一个地址簿样式应用程序,在按下按钮后存储联系人详细信息,然后在下一次加载时恢复它们。

在弄清楚为什么文本似乎没有被保存时遇到问题 - 所以下次我在模拟器中加载应用程序时显然不会加载。

[super viewDidLoad];

    NSFileManager *filemgr;
    NSString *documentsDirectory;
    NSArray *directoryPaths;

    filemgr =[NSFileManager defaultManager];
    directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

    documentsDirectory =[directoryPaths objectAtIndex:0];

    filePath =[[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"userInfo.dat"]];

    if ([filemgr fileExistsAtPath:filePath])
    {
        NSMutableArray *userData;
        userData =[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

        txtFirstName.text =[userData objectAtIndex:0];
        txtLastName.text =[userData objectAtIndex:1];
        txtEmail.text =[userData objectAtIndex:2];
        txtPhone.text =[userData objectAtIndex:3];
        NSLog(@"File Has Been loaded");
    }else
    {
        NSLog(@"Error.");
    }


}

- (IBAction)btnSaveDetails:(id)sender {
    NSMutableArray *contactDetails;
    contactDetails =[[NSMutableArray alloc]init];
    [contactDetails addObject:txtFirstName.text];
    [contactDetails addObject:txtLastName.text];
    [contactDetails addObject:txtEmail.text];
    [contactDetails addObject:txtPhone.text];

    [NSKeyedArchiver archiveRootObject:contactDetails toFile:filePath];

    NSLog(@"File Saved");

}

提前致谢

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

-(id)viewDidLoad
{
        NSMutableArray * userData = [[NSMutableArray alloc] init];

        NSData * downloadedData = [[NSData alloc] initWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userInfo.plist"]];

        if (downloadedData.length)
            [userData setArray:[NSKeyedUnarchiver unarchiveObjectWithData:downloadedData]];

        NSLog(@"userData :%@", userData);

        downloadedData = nil;
}

-(IBAction)btnSaveDetails:(id)sender
{    

   NSMutableArray * contactDetails =[[NSMutableArray alloc]init];

    [contactDetails addObject:txtFirstName.text];

    [contactDetails addObject:txtLastName.text];

    [contactDetails addObject:txtEmail.text];

    [contactDetails addObject:txtPhone.text];

    NSData * contactData = [NSKeyedArchiver archivedDataWithRootObject:contactDetails];

    [contactData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userInfo.plist"] atomically:YES];

    contactData = nil;
}

谢谢!