简体   繁体   中英

Write data to plist

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 eg CLLocations as values for keys? Will it be saved correctly or would the CLLocation need to be broken into lat and lon values?

Thanks

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, eg 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).

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