问题描述
所以我知道 NSManagedObjects
不是线程安全的,从后台线程获取对象的最好方法是使用 [context objectWithId:id ];
,因此传递对象ids而不是实际的对象。
So I know NSManagedObjects
are not thread safe, and the best way to get objects from a background thread is to use [context objectWithId:id];
, and so pass around object ids instead of the actual object.
假设我有一个全局 NSManagedObject
在我的
AppDelegate
(不是最好的设计模式,只是例如) NSManagedObject * myObject;
Let's say I have a global NSManagedObject
in my AppDelegate
(not the best design pattern, but just for example) NSManagedObject *myObject;
从后台线程访问此对象的 objectId
是否安全?像这样:
Is it safe to access this object's objectId
from a background thread? Like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
objectId = appDelegate.myObject.objectId;
//is this thread safe?
}
推荐答案
这不安全,因为不能保证调用 objectID
在 myObject
访问你的块之外的objectID(例如在主线程上),然后在你的块中使用它:
This is not safe, since there's no guarantee that calling objectID
on myObject
is safe. You should access the objectID outside of your block (on the main thread, for example) and then use it within your block. Something like:
NSManagedObjectID *objectID = appDelegate.myObject.objectId;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// use objectID here.
}
这篇关于从后台线程访问NSManagedObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!