如果我没有在创建它们的线程上显式地访问它们,是否可以安全地操作我在线程之外创建的对象? [英] Is it safe to manipulate objects that I created outside my thread if I don't explicitly access them on the thread which created them?

查看:107
本文介绍了如果我没有在创建它们的线程上显式地访问它们,是否可以安全地操作我在线程之外创建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个可可软件,为了保持GUI响应在海量数据导入(Core Data),我需要在主线程外运行导入。

I am working on a cocoa software and in order to keep the GUI responsive during a massive data import (Core Data) I need to run the import outside the main thread.

访问这些对象是安全的,即使我在主线程中创建它们而不使用锁如果,我在线程运行时不显式访问这些对象。

Is it safe to access those objects even if I created them in the main thread without using locks if I don't explicitly access those objects while the thread is running.

推荐答案

对于Core Data,您应该有一个单独的受管对象上下文,用于导入线程,连接到同一个协调器和持久存储。你不能简单地将在主线程使用的上下文中创建的对象抛出到另一个线程中,并期望它们工作。此外,你不能为自己做锁定;您必须至少锁定对象所在的托管对象上下文。但是如果这些对象被你的视图绑定到一个控件,没有钩子,你可以添加上下文的锁定。

With Core Data, you should have a separate managed object context to use for your import thread, connected to the same coordinator and persistent store. You cannot simply throw objects created in a context used by the main thread into another thread and expect them to work. Furthermore, you cannot do your own locking for this; you must at minimum lock the managed object context the objects are in, as appropriate. But if those objects are bound to by your views a controls, there are no "hooks" that you can add that locking of the context to.

没有免费的午餐。

Ben Trumbull解释了为什么你需要使用单独的上下文,以及为什么只是阅读不像你想象的那么简单或安全,在这个伟大的帖子从晚2004在webobjects-dev列表。 (整个线程是伟大的。)他在讨论企业对象框架和WebObjects,但他的建议也完全适用于核心数据。在他的消息的肉中用Core Data替换ECManagedObjectContext和EOF。

Ben Trumbull explains some of the reasons why you need to use a separate context, and why "just reading" isn't as simple or as safe as you might think, in this great post from late 2004 on the webobjects-dev list. (The whole thread is great.) He's discussing the Enterprise Objects Framework and WebObjects, but his advice is fully applicable to Core Data as well. Just replace "EC" with "NSManagedObjectContext" and "EOF" with "Core Data" in the meat of his message.

线程之间共享数据的问题的解决方案在核心数据中,像之前的企业对象框架一样,是不要。如果你进一步想,你真的,真的必须在线程之间共享数据,那么解决方案是保持独立的对象图在线程隔离的上下文,并使用保存通知从一个上下文中的信息告诉其他上下文什么重新获取。 - [NSManagedObjectContext refreshObject:mergeChanges:] 是专为支持此用途而设计的。

The solution to the problem of sharing data between threads in Core Data, like the Enterprise Objects Framework before it, is "don't." If you've thought about it further and you really, honestly do have to share data between threads, then the solution is to keep independent object graphs in thread-isolated contexts, and use the information in the save notification from one context to tell the other context what to re-fetch. -[NSManagedObjectContext refreshObject:mergeChanges:] is specifically designed to support this use.

这篇关于如果我没有在创建它们的线程上显式地访问它们,是否可以安全地操作我在线程之外创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆