Reputation: 26223
I am trying to save Core Data when the user presses the home button. I wanted to do this from -applicationDidEnterBackground:
but it is not getting called. This maybe because you can't save Core Data from here or just because there is not enough time for the operation to complete. It does however work from -applicationWillResignActive:
I am just curious which is the best delegate method to do this in and why -applicationDidEnterBackground:
is not working.
(As you can see from the output both methods are being called, if I remove the save from -applicationWillResignActive:
nothing happens at all, so its not a situation when one is blocking the other)
// 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 ...
This is what I did in the end:
- (void)applicationDidEnterBackground:(UIApplication *)application {
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
[[self model] saveCoreData:@"[ENTERING BACKGROUND]"];
}
Upvotes: 4
Views: 1981
Reputation: 4552
Check out the UIApplicationDelegate protocol reference.
Basically, this is the part that might interest you about 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.
Upvotes: 2