This one has me batty. In applicationWillTerminate I am doing two things: saving some settings to the app settings plist file and updating any changed data to the SQLite database referenced in the managedObjectContext. Problem is it works sometimes and not others. Same issue in the simulator and on the device. If I hit the home button while the app is running, I can only sometimes get the data to store in the plist and into the CoreData store. It seems that it's both works or neither works, and it makes no difference if I switch the execution order (saveState, managedObjectContext or managedObjectContext, saveState). I can't figure out how this can happen. Any help is greatly appreciated. lq
AppDelegate.m
@synthesize rootViewController;
- (void)applicationWillTerminate:(UIApplication *)application {
[rootViewController saveState];
NSError *error;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Handle error
exit(-1); // Fail
}
}
}
RootViewController.m
- (void)saveState {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:self.someInteger forKey:kSomeNumber];
[userDefaults setObject:self.someArray forKey:kSomeArray];
}