3

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

some_id
  • 29,466
  • 62
  • 182
  • 304

1 Answers1

6

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

omz
  • 53,243
  • 5
  • 129
  • 141
  • What about the array of dictionaries? Would it be the same as above except with using array? And it will be fine because the array holds NSDictionaries? – some_id May 26 '11 at 20:45
  • 1
    Arrays of dictionaries are fine, as are arrays of arrays, dictionaries of numbers... you get the point. – omz May 26 '11 at 20:50
  • @omz I tried this method of reading, but for some reason when I try to write on a real device it returns the old data. Any ideas? – MikeIsrael May 03 '12 at 15:07
  • @MikeIsrael I'm guessing you're trying to write into your app bundle. That's not possible on a device. You'll have to copy your file into your Documents directory first. – omz May 03 '12 at 17:11
  • @omz thanks yeah that was the problem, got it working +1 for the great answer – MikeIsrael May 04 '12 at 08:57