2010-07-01 89 views
2

我writeToFile没有保存我的数据到我的.plist。iphone - 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文件夹中。

任何想法?

+0

什么是群路径,你能打印出来吗? – vodkhang 2010-07-01 08:15:42

+0

NSString * path = [[NSBundle mainBundle] pathForResource:@“Groups”ofType:@“plist”]; self.groupPath = path; – john 2010-07-01 08:22:55

+0

看起来它是写给:/用户/我/图书馆/应用程序支持/ iPhone模拟器/ 4.0 /应用程序/.../ Groups.plist 有没有一种方法,我可以把它保存到.plist是在我的工作空间? – john 2010-07-01 08:30:03

回答

3

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

你应该做同样的事情:

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

不能编辑存在于工作区中的文件。

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