4

Possible Duplicate:
iOS: store two NSMutableArray in a .plist file

I've always refrained from using plists as I'm not really sure how to use one.

Could anyone give a simple code example of using a plist? I'm interested in saving an NSArray or NSDictionary to a plist and then retrieving it again later.

Are there any advantages/disadvantages to storing either an NSArray or an NSDictionary? Also, are there any rules with regards to what you can or can't store in a plist?

Community
  • 1
  • 1
Liam George Betsworth
  • 18,373
  • 5
  • 39
  • 42
  • That only answers half the question, but thank you anyway. – Liam George Betsworth Apr 29 '12 at 15:42
  • 1
    Plists can't store all data types, just strings, numbers, booleans, dates, data, arrays, and dictionaries. There is no huge advantage of dictionary over array - if you want named keys use a dictionary and if you want an ordered list use an array. – EricS Apr 29 '12 at 15:44

1 Answers1

11

You can store the following data types in a .plist file as value:

  • NSArray
  • NSMutableArray
  • NSDictionary
  • NSMutableDictionary
  • NSData
  • NSMutableData
  • NSString
  • NSMutableString
  • NSNumber
  • NSDate

With an NSDictionary you can store in a plist an associative array composed by some key-value pair. Use the NSArray if you only want to save a data series.

To save one of the object above on a plist file simply write:

- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"yourFileNameHere"];
}

 //Write to the plist

 [myArray writeToFile:[self dataFilePath] atomically:YES];

 //Read from the plist

 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
     NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
 }
Liam George Betsworth
  • 18,373
  • 5
  • 39
  • 42
Lolloz89
  • 2,809
  • 2
  • 26
  • 41
  • 1
    Thanks, this answers my question pretty well. One more thing though, when I'm calling `writeToFile:atomically:` I'm writing over the entire plist and not just appending data to the end of the file right? – Liam George Betsworth Apr 29 '12 at 16:04
  • 1
    Yes, you're right. If you want to append data to the older array you have to do it manually. Load the array, append then rewrite. – Lolloz89 Apr 29 '12 at 18:10