Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing and Retrieving from a Plist [duplicate]

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?

like image 243
Liam George Betsworth Avatar asked Dec 21 '22 22:12

Liam George Betsworth


1 Answers

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];
 }
like image 102
Lolloz89 Avatar answered Jan 02 '23 19:01

Lolloz89