Reputation: 45
I want to save an NSMutableArray to a file and load it every time my program runs. What is the best solution for this?
This is my example:
// I add a new item to ARRAYLIST
NSString *textNewCategory = [alert textFieldAtIndex:0].text;
[ARRAYLIST insertObject:textNewCategory atIndex:0];
// I save ARRAYLIST
userCategory = [NSUserDefaults standardUserDefaults];
[userCategory setObject:ARRAYLIST forKey:@"newCategory"];
NSLog(@"ARRAYLIST 1:%d", ARRAYLIST.count); // EX: In this case, it has count : 30
//In viewdidload, I get array that I saved before
userCategory = [NSUserDefaults standardUserDefaults];
arrayNewCategory = [[NSMutableArray alloc] initWithArray: [userCategory objectForKey:@"newCategory"]];
ARRAYLIST = arrayNewCategory;
NSLog(@"ARRAYLIST 2:%d", ARRAYLIST.count); // In this moment, it only has count: 29.
I don't understand why the re-loaded array has only 29 items instead of the 30 that I expect.
Upvotes: 0
Views: 286
Reputation: 9387
Save the array to a plist:
[array writeToFile:path atomically:NO]
and retrieve it:
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
Upvotes: 1