0

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!

Karlo A. López
  • 2,548
  • 3
  • 29
  • 56
  • 1
    Initialize the array with the current values from `NSUserDefaults`, then add the new value, then save the updated list back to `NSUserDefaults`. – rmaddy Mar 11 '14 at 22:45

3 Answers3

4

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.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
0

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);
Rich
  • 8,108
  • 5
  • 46
  • 59
0

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.

Josip B.
  • 2,434
  • 1
  • 25
  • 30
  • You are correct but you still do not know when is that "periodically" moment. Calling synchronized can sometimes save your hair in the end :) – Josip B. Mar 11 '14 at 22:58