我想使用 NSOperationQueue
来分派(dispatch) CoreData 操作。但是,操作队列行为并不总是相同的(例如,它在使用线程池的 iOS 4.0/OS 10.6 上使用 libdispatch
进行调度)并且队列可能并不总是使用相同的线程(如 NSManagedObjectContext
要求)。
我可以强制串行 NSOperationQueue
在单个线程上执行吗?
还是我必须为此创建自己的简单排队机制?
最佳答案
Can I force a serial NSOperationQueue to execute on a single thread? Or do I have to create my own simple queuing mechanism for that?
您不需要执行其中任何一项操作。 Core Data 真正需要的是您没有两段代码同时 对托管对象上下文进行更改。在 Concurrency with Core Data 的开头甚至有关于此的注释:
Note: You can use threads, serial operation queues, or dispatch queues for concurrency. For the sake of conciseness, this article uses “thread” throughout to refer to any of these.
真正需要的是在给定的上下文中序列化操作。如果您使用单个线程,这自然会发生,但是如果您将 maxConcurrentOperationCount
设置为 1,NSOperationQueue 也会序列化它的操作,因此您不必担心确保所有操作都发生在同一个线程上。
关于objective-c - NSOperationQueue 指定线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486900/