Search code examples
ioscore-datansmanagedobjectcontextnsmanagedobjectid

How to pass a ManagedObjectID to the main thread


I am saving a ManagedObject on a background thread with its own context. I would then like to send a notification back to the main thread with the managed object context so that I can use its data.

According to the docs it looks like I instead should be passing the id to the main thread rather than the object.

Is this correct, what should I do with that Id then? Should I do a fetch on core data from the main thread with the ID to get a ManagedObject on the main thread?


Solution

  • You're correct in understanding the passing of the object ID back to the main thread. Once you've done that, use the objectWithID: method, passing the NSManagedObjectID sent from the other thread, to get the object out of the main thread's NSManagedObjectContext instance.

    NSManagedObject *objectForThisThread = [managedObjectContextForThisThread objectWithID:managedObjectID];