Search code examples
ioscore-datamagicalrecord

MagicalRecord save does not persist until app is quit the first time and rerun


I am not sure if this is a Core Data issue or a MagicalRecord issue.

My app uses MagicalRecord to help with CoreData use. When the app is run the very first time after install, when I save new objects, and then the app is quit and run again, those objects are not there. However, any new objects created after this first re-run of the app are persisted normally. It only happens when the app is fresh and the database empty. When the app has been run once, even though the database is empty (confirmed by dowbloading the app and extracting the sqlite file and opening it on my Mac), it works from then on out.

In my app delegate I do the following

    [MagicalRecord setupAutoMigratingCoreDataStack];

The app is saving push notifications it receives so the app can list activity that has happened. So when a push notification comes in, this code runs

     _currentNotification = [PNotificationEntry MR_createEntity];

     _currentNotification.* = <new value>; // set all kinds of attributes

     [[NSManagedObjectContext MR_contextForCurrentThread] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
            if (nil != error)
               {
                  NSLog(@"failure to save notification entry");
                  }
               else 
               {
                  NSLog(@"successful save of notification entry"):
                  }
            }];

I know it saves because the magical record logging in the console shows that it is successful and the NSLog shows it, and more importantly, an NSFetchedResultsController that is watching for changes picks up the new object and displays it.

But once the app quits and is rerun, none of the objects that were inserted are in the sqlite file and none show up. But again, as mentioned, once the app has been quit once after installation, it now starts persisting objects correctly and you do see the objects there on the next run of the app.

It does not matter if on the very first run after installation, the app tries to insert an object or not. The second run of the app things work correctly.

I am at a loss on what might be happening.

MagicalRecord version is the latest on github as of last week.


Solution

  • You're probably not seeing the changes because you are using MR_contextForCurrentThread. This method is fundamentally flawed since the introduction of GCD queues, and has been deprecated. I go through this on my blog.

    When you use MR_createEntity, without specifying an NSManagedObjectContext, you need to save the default context, because that's where all your data is:

    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    

    Your cleanup workaround is unnecessary and most likely, losing data.