iphone - writeToFile没有将新条目保存到plist中

时间:2010-07-01 07:53:00

标签: iphone objective-c plist

我的writeToFile没有将我的数据保存到我的.plist。

- (IBAction)clickBtnDone:(id) sender {
 NSLog(@"Done");
 if ([txtGroupName.text length] > 0) {  
  [self dismissModalViewControllerAnimated:YES];
  NSLog(@"Group Name: %@", txtGroupName.text);
  NSMutableArray *newDict = [[NSMutableArray alloc] init];
  [self.groups setObject:newDict forKey:txtGroupName.text];
  NSLog(@"Count:%d", [self.groups count]);

  BOOL success = [self.groups writeToFile:self.groupPath atomically:YES];
  if(success) { 
   NSLog(@"Success Saving New Group");
  } else {
   NSLog(@"Failure Saving New Group");
  }
  [newDict release];
 }
}

这是调试显示的内容:

2010-07-01 00:48:38.586 Contacts[7111:207] Done
2010-07-01 00:48:38.589 Contacts[7111:207] Group Name: C
2010-07-01 00:48:38.590 Contacts[7111:207] Count:3
2010-07-01 00:48:38.592 Contacts[7111:207] Success Saving New Group

但是,当我打开.plist文件时,它仍然只有2个我手动创建的组,而不是新条目。

这些文件位于我的~Documents文件夹中。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

如何初始化groupPath?它应该是文档目录的路径,而不是资源目录的路径。

你应该做类似的事情:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

您无法编辑工作区中存在的文件。

答案 1 :(得分:0)

NSString* plistPath = nil;
NSFileManager* manager = [NSFileManager defaultManager];
 if ((plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"PathTo.plist"])) 
   {
    if ([manager isWritableFileAtPath:plistPath]) 
     {
       NSMutableDictionary* infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
      [infoDict setObject:@"foo object" forKey:@"fookey"];
      [infoDict writeToFile:plistPath atomically:NO];
      [manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:nil];
     }
   }