Storing and Retrieving from a Plist [duplicate]
Asked Answered
H

1

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?

Holsworth answered 29/4, 2012 at 15:19 Comment(2)
That only answers half the question, but thank you anyway.Holsworth
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.Smudge
U
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];
 }
Usable answered 29/4, 2012 at 15:51 Comment(2)
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?Holsworth
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.Usable

© 2022 - 2024 — McMap. All rights reserved.