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?
You can store the following data types in a .plist file as value:
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With