NSMutableArray disappears after app kill or restart using NSKeyedArchiver
I have an app that is storing Task
objects (custom class) inside of a NSMutableArray
. The Task
class conforms to the NSCoding
and NSCopying
protocols, and I have also implemented the encodeWithCoder
and initWithCoder
methods.
When the user adds a new task to an NSMutableArray
list
, I save the array using NSKeyedArchiver
. The list
populates a UITableView
.
The data is being saved, and when I exit the app and reenter, the data is still there. When I use another app for a while and come back, the data is still there. However, when I "kill" the app in the multitasking task manage or restart the device, the data disappears. Here are some important code snippets:
#define kFilename @"epapsTasksFile"
.
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
- (voi开发者_StackOverflowd)viewDidLoad {
NSString *filePath = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
self.list = [[NSKeyedUnarchiver unarchiveObjectWithFile:kFilename] retain];
}
else {
self.list = [NSMutableArray arrayWithCapacity:1];
}
...
}
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *updatedList = [[NSMutableArray alloc] initWithArray:self.list];
[NSKeyedArchiver archiveRootObject:updatedList toFile:kFilename];
}
Why is my app not saving the data when the app is "killed" or the device is restarted? Also, it may be interesting to note that when I restart the iPhone simulator, the data stays in place.
You need to save the data
([NSKeyedArchiver archiveRootObject:updatedList toFile:kFilename];
in applicationWillTerminate
delegate method as as well to save it on termination.
EDIT:
applicationWillTerminate
is not gauranteed in IOS4.0 and above.
Best is to check the return status of archiveRootObject:toFile:
and see if the data is stored properly. As you figured it out, it can be case with wrong file path.
精彩评论