Search code examples
iosswiftcore-datansmanagedobjectcontext

Pointer to a NSManagedObject outside a performBlock


Assume that I have fetched a NSManagedObject within a performBlock on a private NSManagedObjectContext. I have also saved a pointer of the NSManagedObject in the AppDelegate. so basically I am holding it on the 'main thread'. Could this cause any issue? Note that I always access the attributes within a performBlock submitted to the correct context.


Solution

  • No, you cannot do that. A reference to an object from a different context can crash your app.

    There are several solutions to this. For example, your global variable could be a unique attribute that you can use to fetch the object in the right context.

    Some of the operations might be done on the same context as the one in which your global object is held.

    And finally, you can also pass objects between contexts using the objectID, an opaque type NSManagedObjectID. You could initialize your local object in a particular thread with object(with:).