开发者

Saving NSMutableArray to plist? [duplicate]

This question already has an answer here: Closed 11 years ago.

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];
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜