我正在尝试将 bool 值写入plist文件,但我真的不知道我哪里做错了。我什至没有收到任何异常/错误,但相关文件中的值保持不变。此外,文件路径也正确,myDict
的分配显示已经从文件中读取了值。
下面是我写的代码
-(void)SetSettings:(BOOL)SoundOn: (BOOL)GlowOn
{
NSString *pathSettingFile = [[NSString alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"AppSettings" ofType:@"plist"]];
NSMutableDictionary *myDict = [NSMutableDictionary dictionaryWithContentsOfFile:pathSettingFile];
[myDict setObject:[NSNumber numberWithBool:SoundOn] forKey:@"isSoundOn"];
[myDict setObject:[NSNumber numberWithBool:GlowOn] forKey:@"isGlowOn"];
[myDict writeToFile:pathSettingFile atomically:NO];
[myDict release];
[pathSettingFile release];
}
最佳答案
您无法写入主包。您只能从主包中读取。如果您想编写文件,则需要将其放入应用程序的文档目录中。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];
编辑:
如果您需要主包中的 plist,可以先将其复制到文档目录中,然后进行修改。
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){
NSLog(@"File don't exists at path %@", path);
NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
[fileManager copyItemAtPath:plistPathBundle toPath: path error:&error];
}else{
NSLog(@"File exists at path:%@", path);
}
关于iphone - 无法在 plist 文件中写入 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6593627/