【发布时间】:2011-06-13 21:40:20
【问题描述】:
我有一个将Task 对象(自定义类)存储在NSMutableArray 内的应用程序。 Task类符合NSCoding和NSCopying协议,我也实现了encodeWithCoder和initWithCoder方法。
当用户向NSMutableArray list 添加新任务时,我使用NSKeyedArchiver 保存数组。 list 填充 UITableView。
数据正在保存中,当我退出应用重新进入时,数据还在。当我使用另一个应用程序一段时间并回来时,数据仍然存在。但是,当我在多任务任务管理或重新启动设备中“杀死”应用程序时,数据消失了。下面是一些重要的sn-ps代码:
#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 模拟器时,数据仍然存在。
【问题讨论】:
标签: ios nsmutablearray nskeyedarchiver