Home > OS >  Is it thread safe to get context of NSManagedObject instance?
Is it thread safe to get context of NSManagedObject instance?

Time:09-21

I.e. to access the managedObjectContext property of NSManagedObject from other thread? For example:

class StoredObject: NSManagedObject {
    @NSManaged public var interestProperty: String
}

------- somewhere on background -------

let context = storedObject.managedObjectContext // is it safe?
context.perform { [storedObject] in
    // do something with interestProperty
}

---------------------------------------

CodePudding user response:

NSManagedObjectContext is not thread safe. Even if you grab the instance of such an object, using it on a different thread might lead to undefined behaviour.

This is specified in the Apple documentation (emphasis mine):

Core Data is designed to work in a multithreaded environment. However, not every object under the Core Data framework is thread safe. To use Core Data in a multithreaded environment, ensure that:

  • Managed object contexts are bound to the thread (queue) that they are associated with upon initialization.

  • Managed objects retrieved from a context are bound to the same queue that the context is bound to.

So while reading the managedObjectContext property might be thread safe, as that property is readonly, you will not be able to use it without risking race conditions. And you also need to take into consideration the lifetime of the managed object, as unless properly retained, you might end up asking a deallocated managed object for its context.

  • Related