4

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

In the app I'm working on I have a bunch of "Registration" objects that contain some strings,dates and integers. All of these objects are stored in a NSMutableArray when they're created, and I now want to save this array in someway, so that when the user closes the app etc., the content can be stored and restored when app opens again.

I've read that plist is probably the best way to do so, but I can't seem to find any examples, posts etc. that show how to do it?

So basicly: How to I save my NSMutableArray to a plist file when app closes, and how to restore it again?

Community
  • 1
  • 1
David K
  • 3,153
  • 5
  • 18
  • 27
  • - Look at this question: [iOS: store two NSMutableArray in a .plist file](http://stackoverflow.com/questions/6070568/ios-store-two-nsmutablearray-in-a-plist-file) - Maybe this could help too: [save to .plist properity list][3] - Aaaand this: [creating a plist file programatically][2] [2]: http://www.iphonedevsdk.com/forum/iphone-sdk-development/5823-save-plist-properity-list.html#post235567 [3]: http://stackoverflow.com/questions/2292347/creating-a-plist-file-programatically – Sascha Galley Jul 07 '11 at 08:25

1 Answers1

12

NSMutableArray has a method for doing this, if you know exactly where to save it to:

//Writing to file
if(![array writeToFile:path atomically:NO]) {
    NSLog(@"Array wasn't saved properly");
};

//Reading from File
NSArray *array;
array = [NSArray arrayWithContentsOfFile:path];
if(!array) {
    array = [[NSMutableArray alloc] init];
} else {
    array = [[NSMutableArray alloc] initWithArray:array];
};

Or you can use NSUserDefaults:

//Saving it
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"My Key"];

//Loading it
NSArray *array;
array = [[NSUserDefaults standardUserDefaults] objectForKey:@"My Key"];
if(!array) {
    array = [[NSMutableArray alloc] init];
} else {
    array = [[NSMutableArray alloc] initWithArray:array];
};
EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50