Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: Do child contexts ever get permanent objectIDs for newly inserted objects?

I have an app with two managed object contexts setup like this:

  • Parent Context: NSPrivateQueueConcurrencyType, linked to the persistent store.
  • Main Context: NSMainQueueConcurrencyType, child of Parent Context.

When insert a new managed object to the main context, I save the main context and then the parent context like this:

[context performBlockAndWait:^{
    NSError * error = nil;
    if (![context save: &error]) {
        NSLog(@"Core Data save error %@, %@", error, [error userInfo]);
    }
}];

[parentContext performBlock:^{
    NSError *error = nil;
    BOOL result = [parentContext save: &error];
    if ( ! result ) {
        NSLog( @"Core Data save error in parent context %@, %@", error, [error userInfo] );
    }
}];

My understanding is that when the manage object is first created, it has a temporary objectID. Then the main context is saved and this object, with its temporary ID, gets to the parent context. Then the parent context is saved. When this last context is saved, the temporary objectID in the parent context gets transformed into a permanent objectID.

So:

  • Does the permanent object ID ever get propagated automatically back to the main (child) context?
  • When I force to get the object permanent ID with [NSManagedObjectContext obtainPermanentIDsForObjects:error:], then background the app, reactivate it, reload, get the object using main context's objectWithID:, and access a property, I get

    "CoreData could not fulfill a fault for ...".

What is wrong with this approach?
like image 244
Jorge Avatar asked Aug 16 '12 15:08

Jorge


People also ask

Can we have multiple managed object contexts in Core Data?

Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.

What is managed object context in Core Data?

A managed object context represents a single object space, or scratch pad, in a Core Data application. A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects.

What is persistent container in Core Data?

The persistent container gives us a property called viewContext , which is a managed object context: an environment where we can manipulate Core Data objects entirely in RAM.


3 Answers

It is a known bug, hopefully fixed soon, but in general, obtaining a permanent ID is sufficient, provided you do so before you save the data in the first child, and you only include the inserted objects:

[moc obtainPermanentIDsForObjects:moc.insertedObjects.allObjects error:&error]

In some complex cases, it is better to get a permanent ID as soon as you create the instance, especially if you have complex relationships.

How and when are you calling obtainPermanentIDsForObjects?

I do not follow the part about the app crashing. Maybe a better explanation would help.

like image 185
Jody Hagins Avatar answered Oct 22 '22 05:10

Jody Hagins


As Jody said above, when creating a new NSManagedObject in a background thread using a child ManagedObjectContext you must force the creation of a permanent ID by doing the following BEFORE you save:

NSError *error = nil;

[threadedMOC obtainPermanentIDsForObjects:threadedMOC.insertedObjects.allObjects error:&error];

BOOL success = [threadedMOC save:&error];

IMHO, it's not really intuitive to do it this way - after all, you're asking for a permanent ID BEFORE you save! But this is the way it seems to work. If you ask for the permanent ID after the save, then the ID will still be temporary. From the Apple Docs, you can actually use the following to determine if the object's ID is temporary:

BOOL isTemporary = [[managedObject objectID] isTemporaryID];
like image 28
Dino Mic Avatar answered Oct 22 '22 06:10

Dino Mic


Problem still exists in iOS 8.3 Solution in Swift :

func saveContext(context: NSManagedObjectContext?){
   NSOperationQueue.mainQueue().addOperationWithBlock(){
    if let moc = context {
        var error : NSError? = nil
        if !moc.obtainPermanentIDsForObjects(Array(moc.insertedObjects), error: &error){
            println("\(__FUNCTION__)\n \(error?.localizedDescription)\n \(error?.userInfo)")
        }
        if moc.hasChanges && !moc.save(&error){
            println("\(__FUNCTION__)\n \(error?.localizedDescription)\n \(error?.userInfo)")
        }
    }
 }
}

func saveBackgroundContext(){
    saveContext(self.defaultContext)

    privateContext?.performBlock{
        var error : NSError? = nil
        if let context = self.privateContext {

            if context.hasChanges && !context.save(&error){
                println("\(__FUNCTION__)\n \(error?.localizedDescription)\n \(error?.userInfo)")
            }else {
                println("saved private context to disk")
            }
        }
    }
}

Where:

  • defaultContext has concurrencyType .MainQueueConcurrencyType
  • privateContext has concurrencyType .PrivateQueueConcurrencyType
like image 2
CryingHippo Avatar answered Oct 22 '22 04:10

CryingHippo