应用程序退出时,NSManagedObjectContext不会保存。重新推出

时间:2016-01-11 08:31:52

标签: 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]);
}

}

1 个答案:

答案 0 :(得分:1)

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

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

您可以将逻辑移至applicationDidEnterBackground:但如果您的应用崩溃或从Xcode终止,则仍然无法调用此逻辑。