简体   繁体   中英

Not Able to write Boolean in plist file

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

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

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.

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

Seethis answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM