Task
内にオブジェクト(カスタムクラス)を格納しているアプリがありNSMutableArray
ます。Task
クラスはとプロトコルに準拠しておりNSCoding
、とメソッドNSCopying
も実装しました。encodeWithCoder
initWithCoder
ユーザーがに新しいタスクを追加するとき、を使用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シミュレーターを再起動しても、データはそのまま残っていることに注意してください。