我試圖使用從開始iPhone開發這個代碼保存在我的應用程序簡單的文本數據:將數據保存到iOS5的問題
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingFormat:kFileName];
}
- (void)applicationWillTerminate:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:field1.text];
[array addObject:field2.text];
[array addObject:field3.text];
[array addObject:field4.text];
[array writeToFile:[self dataFilePath] atomically:YES];
}
- (void)viewDidLoad { NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
field1.text = [array objectAtIndex:0];
field2.text = [array objectAtIndex:1];
field3.text = [array objectAtIndex:2];
field4.text = [array objectAtIndex:4];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:app];
[super viewDidLoad];
}
此代碼的編寫,並針對iOS 3的偉大工程,但不與iOS 5.如果您只需點擊模擬器中的主頁按鈕關閉它,然後啓動多任務欄並點擊應用程序圖標,數據就會重新加載。但是,當您通過點擊主頁按鈕關閉它時,然後調出多任務欄並關閉它,然後重新啓動應用程序,數據就消失了。我不認爲應用程序收到關於它從多任務欄關閉時被終止的通知,但我不確定自己還是初學者。
我確定我只需要在已有的代碼中添加一行或兩行。有人知道可能是什麼嗎?
非常感謝。我將applicationWillTerminate改爲applicationDidEnterBackground。但是,在viewDidLoad的結尾處,在「name:」下面,它表示UIApplicationWillTerminateNotification。我嘗試將其更改爲UIApplicationWillEnterBackgroundNotification,但出現錯誤。你應該把它放在那裏嗎? – John 2012-01-04 21:32:13
UIApplicationDidEnterBackgroundNotification – 2012-01-04 21:35:14
非常感謝!這非常有幫助。 – John 2012-01-04 21:47:11