【发布时间】:2011-05-18 04:10:38
【问题描述】:
我一直在 iPad 应用程序中使用 Core Data,我可以成功地在应用程序内保存和获取数据。但是,当完全关闭应用程序时,完全退出,将其从多任务处理中取出,然后该数据就消失了。
那么当应用程序关闭时,Core Data 是否会在任何地方保留这些数据?还是我需要去其他地方看看?
编辑:这是在应用程序委托didFinishLaunchingWithOptions:[[[UIApplication sharedApplication] delegate] managedObjectContext];,然后我在 UIView 子类中有:context_ = [(prototypeAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];。
这是在应用委托中预制的 NSPersistentStoreCoordinator 代码:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"prototype.sqlite"];
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
}
到目前为止,我正在使用它来获取数据:
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:context_];
[fetch setEntity:testEntity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
[fetch setPredicate:pred];
NSError *fetchError = nil;
NSArray *fetchedObjs = [context_ executeFetchRequest:fetch error:&fetchError];
if (fetchError != nil) {
NSLog(@"fetchError = %@, details = %@",fetchError,fetchError.userInfo);
}
noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:@"savedText"];
这是为了保存数据:
NSManagedObject *newDatedText;
newDatedText = [NSEntityDescription insertNewObjectForEntityForName:@"DatedText" inManagedObjectContext:context_];
[newDatedText setValue:noteTextView.text forKey:@"savedText"];
[newDatedText setValue:datePicker.date forKey:@"dateSaved"];
NSError *saveError = nil;
[context_ save:&saveError];
if (saveError != nil) {
NSLog(@"[%@ saveContext] Error saving context: Error = %@, details = %@",[self class], saveError,saveError.userInfo);
}
【问题讨论】:
-
你是如何设置你的 managedObjectContext 的?为了在退出后保存数据,您需要设置 NSPersistentStoreCoordinator。
-
更新了更多细节的问题。
-
您的保存代码肯定是错误的。您绝对不得查看
saveError的值,除非对-save:的调用返回NO。这样做是一个编程错误,并且可能使您的应用程序崩溃。-save:不保证会保留该变量的有效值,除非它返回 NO。所以你应该使用if (![context_ save:&saveError]) { /* read saveError */ }。
标签: iphone objective-c core-data load save