プロパティ値を applicationDidEnterBackground に保存するには: 次のように、クラスの viewDidLoad メソッドに通知オブザーバーを追加できます。
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
viewDidUnload では、これを追加する必要があります:
[[NSNotificationCenter defaultCenter] removeObserver:self];
また、これら 2 つのメソッドをクラス .m-file に追加します (以下に、私のアプリケーションの 1 つからの例を示します)。
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithInt:self.event.eventID]];
[array addObject:self.event.eventName];
[array addObject:[NSNumber numberWithDouble:[self.event.ticketPrice doubleValue]]];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
そして、このメソッドはファイルからデータをロードし、viewDidLoad で呼び出します。
- (void)loadEventFromEventPlist {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
self.event.eventID = [[array objectAtIndex:0] intValue];
self.event.eventName = [array objectAtIndex:1];
self.event.ticketPrice = [NSNumber numberWithDouble:[[array objectAtIndex:2] doubleValue]];
[array release];
}
}
ファイル名を取得するには、このメソッドが必要です。
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}