为什么这不起作用? - 将数据写入plist

时间:2014-11-20 10:34:41

标签: objective-c xcode macos cocoa

我使用以下代码修改plist但无效:

-(IBAction)modifyPlist:(id)sender{
NSBundle *mainBundle=[NSBundle mainBundle];
NSString *path=[mainBundle pathForResource:@"Preferences" ofType:@"plist"];
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
[dict setValue:@"YES" forKey:@"test"];
[dict writeToFile:path atomically:YES];
}

有谁知道为什么它不会将plist值'test'从NO更改为YES?

2 个答案:

答案 0 :(得分:1)

冗长简短:因为你无法写入应用包。

答案 1 :(得分:0)

您正在写入应用的捆绑目录。可以从该目录中的plist中读取,但不允许您写入自己的应用程序资源,这样就无法工作了。相反,您必须写入Documents目录中的plist,您可以以类似的方式获取路径:

// Find the path to the plist in the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Preferences.plist"];
相关问题