开发者

iphone - writeToFile not saving new entry into plist

My writeToFile is not saving my data to my .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");
  } 开发者_StackOverflowelse {
   NSLog(@"Failure Saving New Group");
  }
  [newDict release];
 }
}

Here is what the debug shows:

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

However, when I open the .plist file, it still has only 2 groups that I had created manually, and not the new entry.

The files are located in my ~Documents folder.

Any ideas?


How you have initialized groupPath? It should be the path of document directory, not the path of resource directory.

You should do something similar :

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

You can not edit the file that is present in the workspace.


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];
     }
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜