0

我在尝试在线程化 NSOperation 中执行一些核心数据操作时遇到了很多问题。

目前,我在我的应用程序委托中创建了一个托管对象上下文,它纯粹用于我的线程化 NSOperations。我设置了一个最大并发为 1 的 NSOperationQueue,因此每个操作都是连续执行的。对于每个操作(从 Internet 获取数据并创建新的托管对象),我都会将上下文传递给它以供使用。创建新对象后,我保存并重置上下文以供下一个操作使用。但是,我在执行此操作时间歇性地遇到 malloc 错误,并且我花了几天时间试图弄清楚它,这似乎与它的线程化方式有关。

我得到的错误可以在这个相关的堆栈溢出问题中看到。

当我只是将托管对象的属性设置为对象时,会发生 malloc 错误NSNumber。这也是我第一次设置该属性,所以我没有过度释放自己!我根本想不通,我无法使用 GuardMalloc 重现错误,它只是不会发生!就好像错误发生在其他被触发的地方,但我不知道在哪里!

我所能推断的就是这个错误与我如何设置整个事情有关。我尝试自己运行该操作而不是将其添加到 中NSOperationQueue,它似乎工作正常(尽管它挂起主线程!)。

当进行保存时,我还需要上下文来通知我的应用程序中的其他上下文,所以我观察它的NSManagedObjectContextDidSaveNotification通知。但是,由于保存是在 NSOperation (其他线程)中执行的,因此是否会出现问题,因为通知仅在其运行的线程上分派?

4

3 回答 3

2

Resurrecting an old question, but this might help someone - I ran into similar problems with the same setup described here (dedicated context for each NSOperation, max concurrency of one), and I found out that it was due to the fact that I was creating the NSOperation-dedicated context on the main thread, and then I tried to use it in an NSOperation thread. Once I moved context creation into the NSOperation's main function, the problems were gone.

于 2010-10-29T12:45:11.843 回答
2

你读过 Core Data Programming Guide 的Multi-Threading with Core Data部分吗?

于 2009-11-22T18:21:21.800 回答
0

Right, I've managed to get it all working now, much to my relief. After days of messing around, I decided to rewrite all the code to do with the threading and core data and I'm no longer getting the malloc errors. It is a rather complex setup so there must have been something pretty obscure in there!

于 2009-11-22T20:55:32.843 回答