views:

52

answers:

1

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];

}
A: 

Apologies for the lame question. I'll answer it myself in case anyone comes across it with a similar problem. There were two errors taking place simultaneously, thus the appearance the applicationWillTerminate was not being called. The first was a varchar length error in my xcdatamodel. A few of my SQLite rows were trying to save strings which exceeded the varchar length I had set as the maximum in the xcdatamodel. This only appeared on certain records, and thus appeared to be causing inconsistent saves. The second problem was incorrectly saving a possible nil array value to the plist. When I fixed both errors the problem has disappeared.

In the meantime I decided to save to the plist every time a related value is changed rather than on applicationWillTerminate. I am also saving to the Core Data managedObjectContext every time a value is changed, rather than on applicationWillTerminate since a few hundred records could possibly be changed before the app is terminated. (I'm hoping this isn't bad form or causes other issues.)

Lauren Quantrell