我有一个将Task
对象(自定义类)存储在NSMutableArray
. 该类Task
符合NSCoding
andNSCopying
协议,我也实现了encodeWithCoder
andinitWithCoder
方法。
当用户向 中添加新任务时NSMutableArray
list
,我使用NSKeyedArchiver
. list
填充UITableView
一个.
数据正在保存,当我退出应用程序并重新进入时,数据仍然存在。当我使用另一个应用程序一段时间并回来时,数据仍然存在。但是,当我在多任务任务管理或重新启动设备中“杀死”应用程序时,数据消失了。以下是一些重要的代码片段:
#define kFilename @"epapsTasksFile"
.
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
- (void)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];
}
为什么当应用程序被“杀死”或设备重新启动时,我的应用程序不保存数据?此外,有趣的是,当我重新启动 iPhone 模拟器时,数据仍然存在。