我只有OS X 10.9,非文档应用程序
当我没有在托管对象上下文中明确调用-save:
时,Core Data何时自行调用-save:
?
到目前为止,我只是发现它在退出应用程序之前已经保存了。
答案 0 :(得分:2)
我不认为moc会自行保存
答案 1 :(得分:2)
嗯...在iOS中答案很简单。它永远不会。由于NSManagedObjectContext的线程依赖性,我很想说这对OSX来说是相同的。
NSManagedObjectContext保存自己是没有意义的。
如果用户在创建对象的一半时间退出应用并且未完全创建对象,会发生什么?它会在半完成状态下保存吗?
答案 2 :(得分:2)
如果你选中了核心数据"在创建一个新的Xcode项目时,应该在你的app delegate中找到它:
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&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.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
因此,当终止应用程序时,它将显式调用save。
正确的答案是:只有在您上面调用save:
时才会保存上下文。但是使用xcode模板可以为你设置。
上面的代码适用于iOS,对于Mac OS X,它看起来像
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
// Save changes in the application's managed object context before the application terminates.
if (!_managedObjectContext) {
return NSTerminateNow;
}
if (![[self managedObjectContext] commitEditing]) {
NSLog(@"%@:%@ unable to commit editing to terminate", [self class], NSStringFromSelector(_cmd));
return NSTerminateCancel;
}
if (![[self managedObjectContext] hasChanges]) {
return NSTerminateNow;
}
NSError *error = nil;
if (![[self managedObjectContext] save:&error]) {
// Customize this code block to include application-specific recovery steps.
BOOL result = [sender presentError:error];
if (result) {
return NSTerminateCancel;
}
NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:question];
[alert setInformativeText:info];
[alert addButtonWithTitle:quitButton];
[alert addButtonWithTitle:cancelButton];
NSInteger answer = [alert runModal];
if (answer == NSAlertFirstButtonReturn) {
return NSTerminateCancel;
}
}
return NSTerminateNow;
}
也会调用save:
方法。