获取 NSManagedObject 实例的上下文是否线程安全?

Is it thread safe to get context of NSManagedObject instance?

即从其他线程访问 NSManagedObject 的 managedObjectContext 属性?例如:

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
}

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

NSManagedObjectContext 不是线程安全的。即使您获取了此类对象的实例,在不同的线程上使用它也可能会导致未定义的行为。

这是Apple中指定的documentation(强调我的):

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.

因此,虽然读取 managedObjectContext 属性 可能是线程安全的,因为 属性 是只读的,您将无法在不冒竞争条件的情况下使用它。并且您还需要考虑托管对象的生命周期,因为除非正确保留,否则您最终可能会向已释放的托管对象询问其上下文。