iphone – 用户退出应用程序时保存核心数据?

当用户按下主页按钮时,我正在尝试保存Core Data.我想从-applicationDidEnterBackground执行此操作:但它没有被调用.这可能是因为您无法从此处保存Core Data或仅因为没有足够的时间来完成操作.然而,它确实起作用于-applicationWillResignActive:我只是好奇哪个是最好的委托方法来执行此操作以及为什么-applicationDidEnterBackground:不起作用.

(正如你从输出中看到的那样,两个方法都被调用,如果我从-applicationWillResignActive中删除了保存:根本没有任何事情发生,所以当一个人阻塞另一个时不是这种情况)

// CALLS SAVE
- (void)applicationWillResignActive:(UIApplication *)application {
    [[self model] saveCoreData:@"SAVE FROM: applicationWillResignActive"];
    NSLog(@"APPDEL: %s", __PRETTY_FUNCTION__);
}

// DOES NOT CALL SAVE
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[self model] saveCoreData:@"SAVE FROM: applicationDidEnterBackground"];
    NSLog(@"APPDEL: %s", __PRETTY_FUNCTION__);
}

.

// CONSOLE OUTPUT
2013-03-21 cvb[6724:907] APPDEL: -[AppDelegate applicationWillResignActive:]
2013-03-21 cvb[6724:907] APPDEL: -[AppDelegate applicationDidEnterBackground:]
2013-03-21 cvb[6724:907]  
2013-03-21 cvb[6724:907] SAVE: SAVE FROM: applicationWillResignActive
2013-03-21 cvb[6724:907] SAVE: Saving successful ...

编辑:

这就是我最后所做的:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    [[self model] saveCoreData:@"[ENTERING BACKGROUND]"];
}

最佳答案 查看
UIApplicationDelegate protocol reference.

基本上,这是您可能对applicationDidEnterBackground感兴趣的部分:

You should perform any tasks relating to adjusting your user interface
before this method exits but other tasks (such as saving state) should
be moved to a concurrent dispatch queue or secondary thread as needed.
Because it’s likely any background tasks you start in
applicationDidEnterBackground: will not run until after that method
exits, you should request additional background execution time before
starting those tasks. In other words, first call
beginBackgroundTaskWithExpirationHandler: and then run the task on a
dispatch queue or secondary thread.

点赞