不能在plist文件中写入布尔值

MGD*_*MGD 2 iphone xcode objective-c ios4

我正在尝试将布尔值写入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];
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*nte 6

你不能写入主包.您只能从主包中读取.如果要编写文件,则需要将其放入应用程序的文档目录中.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您需要主捆绑中的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);
    }
Run Code Online (Sandbox Code Playgroud)