在这种情况下,@synchronize 是否可以防止竞争条件?
我想在后台线程和 NSOperationQueue 中使用 Core Data。现在我想为什么我不应该创建一个类来保存所有具有 NSManagedObjectContext 属性的核心数据堆栈内容,然后使该属性成为原子属性?
关于 @synchronize(self) {...}
我不确定的一件事是:假设我有一个被认为是线程安全的属性:
@property (retain) NSManagedObjectContext *moc;
每个 NSOperation 或线程都访问一个 CoreDataTools< /code> 具有此 moc 属性的类。他们像这样访问这个 moc 属性:
// Assume: Inside an NSOperation or new thread here...
NSManagedObjectContext *moc = [[CoreDataTools sharedInstance] moc];
// Do a lot of things with moc. Add and remove 20 objects.
这真的有效吗?我不明白这个锁什么时候有效。只是在实际访问该房产的情况下吗?或者我可以安全地使用 NSManagedObjectContext 实例,直到 NSOperation 或后台线程的调用方法完成并返回吗?
我知道 NSManggedObjectContext 有一个 -lock 方法。我想知道这是否有效。
I want to use Core Data in background threads and NSOperationQueue. Now I thought why shouldn't I just create a class holding all the Core Data stack things with a property of NSManagedObjectContext, and then just make this property atomic?
One thing I'm not sure about @synchronize(self) {...}
is this: Assume I have a property that's considered thread-safe:
@property (retain) NSManagedObjectContext *moc;
Every NSOperation or thread accesses an CoreDataTools
class which has this moc property. They access this moc property like this:
// Assume: Inside an NSOperation or new thread here...
NSManagedObjectContext *moc = [[CoreDataTools sharedInstance] moc];
// Do a lot of things with moc. Add and remove 20 objects.
Would this be effective at all? I don't understand WHEN this lock is effective. Just in the event of actually accessing the property? Or can I safely work with the NSManagedObjectContext instance until the NSOperation or called method of the background thread is done and returns?
I know NSMangagedObjectContext has a -lock method. I want to know in general if this would work or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不。每个线程都应该有自己的托管对象上下文。
更多信息:与核心数据的并发
No. Each thread should have its own managed object context.
More info: Concurrency with Core Data