modifying a plist is not working

时光毁灭记忆、已成空白 提交于 2019-12-17 17:11:42

问题


i have to modify a BOOL value in my plist file stored with the bundle.i am able to access the dictionary which i have to modify .from nslogging i can see that dict is updated with the new value ,but the problem is when i check the plist in bundle it is not being modified.any clue on why it is not updating the plist

  NSString* plistPath = nil;
        NSFileManager* manager = [NSFileManager defaultManager];
        if (plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"TopicsList.plist"]) 
        {
            if ([manager isWritableFileAtPath:plistPath]) 
            {
                NSMutableArray* dictarrays = [NSMutableArray arrayWithContentsOfFile:plistPath];
                NSMutableDictionary *dict=[dictarrays objectAtIndex:indexPath.row];
                NSLog(@"%@ ",dict );

                [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isPaid"];

                NSLog(@"%@ ",dict );
                [dict writeToFile:plistPath atomically:NO];
                    NSLog(@"%@ ",dict );
                [manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:&error];
            }
        }

回答1:


Is the plist a part of your resources? Not sure if we can edit a plist there. Copy the plist to your app's Documents folder and update it there.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"TopicsList.plist"];

success = [fileManager fileExistsAtPath:plistPath];
if(!success){
    //file does not exist. So look into mainBundle
    NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TopicsList.plist"];
    success = [fileManager copyItemAtPath:defaultPath toPath:plistPath error:&error];
}

Now whatever changes you need to make to the plist or read data from the plist, read it from the copy in Documents folder.




回答2:


You must store your plist in the documents directory. After that, you must also save the plist upon leaving the app. Otherwise, the plist is in the main bundle and cannot be modified.




回答3:


Is there any error

Check with

NSError *error = nil
[dict writeToFile:plistPath atomically:YES encoding:NSASCIIStringEncoding error:&error];

if (error) {
  NSLog(@"Error: %@", [error description]);
} else {
NSLog(@"Success");
}


来源:https://stackoverflow.com/questions/6368752/modifying-a-plist-is-not-working

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