Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving NSMutableArray to plist? [duplicate]

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?

like image 374
David K Avatar asked Dec 16 '22 12:12

David K


1 Answers

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];
};
like image 114
EmilioPelaez Avatar answered Dec 31 '22 05:12

EmilioPelaez