3
votes

Using RestKit v0.20.0-rc1, I've managed to successfully create CoreData mappings and import objects from bundled JSON files and have the data persist for multiple builds. However, when I create my own entity and save it, the entity disappears immediately upon next build if I use [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext, but persists properly if I use [RKManagedObjectStore defaultStore].persistentStoreManagedObjectContext.

    UserAccount *userAccount = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:managedObjectContext];
    userAccount.userID = @(userID);
    [userAccount addContactMethodsObject:phone];
    NSError *error = nil;
    if(![managedObjectContext save:&error])
        NSLog(@"%@", error);

Using either managedObjectContext saves without errors in the above code, and any fetches from the same context returns the entity properly. But upon subsequent builds, fetches will always return nil if I use mainQueueManagedObjectContext, even though the above code is run on the main thread.

Is there anything I'm missing?

1

1 Answers

9
votes

When you use save: on a context created using mainQueueManagedObjectContext, it won't persist its changes to the store. According to the documentation for RKManagedObjectStore (bolding mine):

The managed object context hierarchy is designed to isolate the main thread from disk I/O and avoid deadlocks. Because the primary context manages its own private queue, saving the main queue context will not result in the objects being saved to the persistent store. The primary context must be saved as well for objects to be persisted to disk.

If you want to persist your changes and still use a mainQueueManagedObject context, try using

- (BOOL)saveToPersistentStore:(NSError **)error

That will kick the changes up the context hierarchy.

The relevant documentation for RKManagedObjectStore can be found at http://restkit.org/api/latest/Classes/RKManagedObjectStore.html#//api/name/persistentStoreManagedObjectContext

The documentation for restkit's NSManagedObject category can be found at http://restkit.org/api/0.20.0-pre3/Categories/NSManagedObjectContext+RKAdditions.html