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 开发者_StackOverflow中文版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.
See this answer
精彩评论