Not Able to write Boolean in plist file

时光怂恿深爱的人放手 提交于 2019-12-24 04:59:26

问题


I am trying to write Boolean value to the plist file, But I really don't know where I'm doing wrong. I am not even getting any Exception/Error yet the values remain unchanged in the concerned file. Furthermore file path is correct too, the allocation of myDict shows that the values ve been read from the file.

Following is the code I have written

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

回答1:


You can not write in to main bundle. You only can read from main bundle. If you want to write an file you need to place it in to the documents directory of your app.

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

Edit:

If you need the plist from the main bundle you can copy it first in to the documents directory then modify it.

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



回答2:


You cannot write/modify the files which are in your resource. they are only meant for reading. Try creating the same(plist file) in the documnets directory of your application.




回答3:


What the [myDict writeToFile:pathSettingFile atomically:NO]; returns? I think you can't write to your file.

See this answer



来源:https://stackoverflow.com/questions/6593627/not-able-to-write-boolean-in-plist-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!