Updating and saving data in plist

▼魔方 西西 提交于 2019-11-28 10:23:48

The easiest way to create a dictionary from a plist is to use the method dictionaryWithContentsOfFile:,

For example, to load a plist from your resources:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"playerData" ofType:@"plist"];
NSMutableDictionary *plistdict = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];

Writing a plistdict is equally simple:

[plistdict writeToFile:filePath atomically:YES];

Note that you can't write into your app's resources, so you'll have to create a different path, e.g. in your Documents directory for your plist.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *docfilePath = [basePath stringByAppendingPathComponent:@"playerData.plist"];
[plistdict writeToFile:docfilePath atomically:YES];

Now retrieve data from plist again.

 NSMutableDictionary *plistdict = [NSMutableDictionary dictionaryWithContentsOfFile:docfilePath];

Add your content in plistDict and write it again.

the method writeToFile:atomically returns a BOOL result. I guess the file is not being saved at all.

The reason why your game works correctly is because the application reads the data from Dictionary (which is populated on launch once), not directly from plist file every time (and it shouldn't either).

Check to see the return value of writeToFile:atomically method to determine whether file is actually being saved or not.

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