0

I am trying to save a NSMutableArray when the app shuts down, and then load it on startup to a tableview.

Here's my code:

- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:_savedText forKey:@"savedText"];
}

- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super initWithCoder:decoder])) {
    _savedText = [decoder decodeObjectForKey:@"savedText"];
}
return self;
}

I use this code to save the MutableArray:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_savedText];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"savedText"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

And this to load it:

- (void)viewDidLoad {
    NSData *savedData = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedText"];
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:savedData];
    array = [_savedText copy];
}

There are no errors, but the table view is empty on startup. Have I forgotten something?

1 Answers1

0

You should read the data from the defaults and set to _savedText object. You are reading the data into var named array and then assigning array = [_savedText copy]. This will probably be nil. It should be the reverse.

- (void)viewDidLoad {
    NSData *savedData = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedText"];
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:savedData];
    _savedText = [array copy];
}
Shanti K
  • 2,873
  • 1
  • 16
  • 31