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 开发者_如何学JAVAapp 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?
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];
};
精彩评论