Reputation: 4540
I could not find why the core data NSManagedObjectContext not get saved when my app quits and re-launch. Every time when i quit the app and re-lanch, database is empty
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();
}
}
}
Save to core data
// 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]);
}
}
Upvotes: 1
Views: 485
Reputation: 119031
applicationWillTerminate:
is basically never used in version of iOS after 4 (when background running came in). You should not rely on it for anything.
You should generally be saving the context after updates rather than waiting for app termination.
You can move your logic to applicationDidEnterBackground:
but this still won't be called if your app crashes or is terminated from Xcode.
Upvotes: 1