【问题标题】:NSManagedObjectContext does not saved when the App Quits & Relaunches应用退出和重新启动时不保存 NSManagedObjectContext
【发布时间】:2016-01-11 08:31:52
【问题描述】:

当我的应用退出并重新启动时,我找不到核心数据 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]);
}

}

【问题讨论】:

  • 您是如何终止应用程序的?除非您禁用后台模式,否则将永远不会调用该委托方法。
  • 只需从 xcode 退出应用程序或退出设备上正在运行的应用程序
  • 为什么要从问题中删除代码?这会使提供的答案无效。
  • @adiga 有一些方法/对象名称我不能让其可见
  • 请不要破坏您的帖子。通过在 Stack Exchange 网络上发布,您已授予 SE 分发该内容的不可撤销的权利(在 CC BY-SA 3.0 license 下)。根据 SE 政策,任何破坏行为都将被撤销。如果您想取消此帖子与您的帐户的关联,请参阅What is the proper route for a disassociation request?

标签: ios objective-c core-data


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    相关资源
    最近更新 更多