Write data to plist

雨燕双飞 提交于 2019-12-22 10:44:49

问题


I would like to read data from a plist, add some elements and the write the data to a plist.(update a plist).

I want to have the plist hold an array of dictionaries, read this array into my app, add dictionaries and then write the array back to the plist.

How is this done? Im also not sure where and how to create the plist on the apps first launch. or should it be placed in the bundle from the beginning?

Another thing I am not sure about is if the plist dictionaries can hold e.g. CLLocations as values for keys? Will it be saved correctly or would the CLLocation need to be broken into lat and lon values?

Thanks


回答1:


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:@"MyPlist" ofType:@"plist"];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];

Writing a plist is equally simple:

[dict 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, see NSSearchPathForDirectoriesInDomains)

Plists can only contain instances of NSDictionary, NSArray, NSNumber and NSString, so you can't put a CLLocation in a Plist without conversion. If you need to save non-Plist objects, have a look at NSKeyedArchiver. It can create files and NSData objects from anything that adopts the NSCoding protocol (CLLocation does).



来源:https://stackoverflow.com/questions/6144670/write-data-to-plist

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