You are missing a line of code there:
self.tasks = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:@"tasks"];
As far as I can tell, you're not initially setting your ".tasks
" property, so adding that bit may fix the problem.
Question
Im having trouble with my nsmutablearray in NSUserdefaults, this array every time I relaunch the app erases the objects that already are there and put the new ones, so I need help to prevent these to happen, Thanks and this is my code;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (!self.tasks) self.tasks = [NSMutableArray new];
[self.tasks addObject:textField.text];
[userDefaults setObject:self.tasks forKey:@"tasks"];
//[userDefaults synchronize];
NSLog(@"tasks:%@", [[NSUserDefaults standardUserDefaults]objectForKey:@"tasks"]);
NSLog(@"number of tasks:%d", self.tasks.count);
And Im reading it in a tableview this way:
cell.taskTitle.text = (self.TasksArray)[indexPath.row];
Thanks!
Solution
You are missing a line of code there:
self.tasks = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:@"tasks"];
As far as I can tell, you're not initially setting your ".tasks
" property, so adding that bit may fix the problem.
OTHER TIPS
You need to get it from user defaults first as rmaddy suggests. Your nil
check will then create a new array if its never been created/saved before.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.tasks = [[userDefaults objectForKey:@"tasks"] mutableCopy];
if (!self.tasks) self.tasks = [NSMutableArray new];
[self.tasks addObject:textField.text];
[userDefaults setObject:self.tasks forKey:@"tasks"];
//[userDefaults synchronize];
NSLog(@"tasks:%@", [[NSUserDefaults standardUserDefaults]objectForKey:@"tasks"]);
NSLog(@"number of tasks:%d", self.tasks.count);
I see you never call [[NSUserDefaults standardUserDefaults] synchronize];
Once you finish with changes of your object you should call it since it saves your changes to disk.