无法在Plist文件中保存数据

时间:2016-01-15 07:05:56

标签: ios objective-c

我有一个名称文本字段,以及三个文本字段,用于电话号码,如homePhone,workPhone和cellPhone。当我单击“保存”按钮将数据保存到plist文件时,它不起作用。请帮忙。

我的代码如下:

在.m文件中保存按钮代码

- (IBAction)btnSave:(id)sender
{
  NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsPath = [paths objectAtIndex:0];

    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

    // set the variables to the values in the text fields
    self.personName = nameEntered.text;
    self.phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
    [phoneNumbers addObject:homePhone.text];
    [phoneNumbers addObject:workPhone.text];
    [phoneNumbers addObject:cellPhone.text];

    // create dictionary with values in UITextFields
    NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];

    NSString *error = nil;
    // create NSData from dictionary
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

    // check is plistData exists
    if(plistData)
    {
        // write plistData to our Data.plist file
        [plistData writeToFile:plistPath atomically:YES];
    }
    else
    {
        NSLog(@"Error in saveData: %@",error);
        //[error release];
    }
}

1 个答案:

答案 0 :(得分:0)

我通过将静态值传递给字典和数组来执行代码。它的工作正常。您的数据中可能包含一些nil值。这可能会导致崩溃。

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); // get documents path
NSString *documentsPath = [paths objectAtIndex:0];
NSString * personName = @"Bharath";
NSMutableArray * phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
[phoneNumbers addObject:@"123"];
[phoneNumbers addObject:@"123"];
[phoneNumbers addObject:@"123"];

NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];

NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

// check is plistData exists
if(plistData)
{
    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];
    NSLog(@"done");
}
else
{
    NSLog(@"Error in saveData: %@",error);
    //[error release];
}

plist数据是,                         名称     巴拉斯     手机              123         123         123               

Check my screenshot