ios - 当 App 退出并重新启动时,NSManagedObjectContext 不会保存

标签 ios objective-c core-data

我找不到为什么当我的应用程序退出并重新启动时核心数据 NSManagedObjectContext 没有得到保存。每次我退出应用程序并重新启动时,数据库都是空的

AppDelegate

- (void)applicationWillTerminate:(UIApplication *)application
{
[[ShowScreenManager sharedInstance] reset];

// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
[self.tracker set:kGAISessionControl value:@"end"];

- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != 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();
    }
}


}

保存到核心数据

// get manageObjectContext
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName"
                                          inManagedObjectContext:context];

[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
fetchRequest = nil;

if(fetchedObjects.count == 0){
    // insert
    anItem = [NSEntityDescription
                   insertNewObjectForEntityForName:@"SomeName"
                   inManagedObjectContext:context];
}
else{
    // update
    anItem = [fetchedObjects objectAtIndex:0];
}

aSequnce.all = strSequnce;


// save context
if (![context save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}

}

最佳答案

applicationWillTerminate: 在 iOS 4 之后的版本中基本上从未使用过(当后台运行出现时)。你不应该依赖它做任何事。

您通常应该在更新后保存上下文,而不是等待应用终止。

您可以将您的逻辑移动到 applicationDidEnterBackground:,但如果您的应用程序崩溃或从 Xcode 终止,它仍然不会被调用。

关于ios - 当 App 退出并重新启动时,NSManagedObjectContext 不会保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34717022/

相关文章:

ios - 使用 Swift 检查为表格 View 单元格中的文本字段选择的行?

ios - 子类 uiwindow 不会旋转到水平方向

ios - 推送通知时如何在 ViewController 上执行操作并检索其数据

objective-c - 设计和逻辑 - 保存重新排序的 UITable 行的最有效方法

ios - Cordova & CORS (iOS)

objective-c - 获取 "Warning may not respond to a"消息 iphone

ios - Xcode 5 & OSX Mavericks 为 iOS6.1 编译不工作

objective-c - 如何在 iOS 5.1 上将回调函数传递给 sqlite3_exec?

swift - 我是否应该在核心数据中将日期字段分解为月、日和年,以便轻松地按月和年分组和获取日期?

ios - 关闭和打开应用程序后核心数据约束工作错误(Swift)