无法将数据保存到plist中

时间:2014-12-06 06:44:47

标签: ios objective-c xcode plist

我使用了一个旧示例将数据保存到plist。来自plist的数据工作正常,但是当我尝试将数据保存到plist中时它没有更改或编辑。我没有得到任何错误按摩。我的代码保存数据是 -

 -(void)saveData
 {
   // get paths from root direcory
   NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
   // get documents path
   NSString *documentsPath = [paths objectAtIndex:0];
   // get the path to our Data/plist file
   NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

  // set the variables to the values in the text fields
  personName = self.nameEntered.text;
  phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
  [phoneNumbers addObject:self.homePhone.text];
  [phoneNumbers addObject:self.workPhone.text];
  [phoneNumbers addObject:self.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);
  }
}

2 个答案:

答案 0 :(得分:0)

你应该从字典到文件。它将它作为一个plist保存。

NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];

NSLog(@"Dictionary is %@", plistDict);    
NSLog(@"Saving to %@", plistPath);

[plistDict writeToFile:plistPath atomically:YES];

我假设你的plistPath是合法的。

答案 1 :(得分:0)

你的代码非常好。我在我的机器上尝试了相同的代码,工作正常。如果您仍然面临同样的问题,那么您可以使用以下api并检查从NSData

创建dictionary
  

+(NSData *)dataWithPropertyList:(id)plist格式:(NSPropertyListFormat)格式   options:(NSPropertyListWriteOptions)opt error :( out NSError **)error