开发者

Core Data concurrency (NSOperation)

In Apple docs it is written:

...you should create the context in main (for a serial queu开发者_如何转开发e) or start (for a concurrent queue).

But I really don't get what is the difference. Why can't I create context in main for the concurrent queue? I tried that and it works absolutely the same as if I did that in start.

There is also another thing that confuses me. From docs for the start method:

...If you are implementing a concurrent operation, you must override this method and use it to initiate your operation.

So again, why can't I initialize everything in main (or maybe should not initialize)?


There may be a difference between what you're calling 'context' and 'concurrent' and what Apple means by the terms. They use 'concurrent' in a specific (and confusing) way. This section from Managing Concurrency With NSOperation might help:

There are a number of different ways that you can use NSOperation, but the most common is to write a custom subclass and override one method: main. The main method gets called to perform the operation when the NSOperationQueue schedules it to run. NSOperation classes written in this way are known as non-concurrent operations, because the developer is not responsible for spawning threads—multi-threading is all handled by the super class. (Don’t be confused by the terminology: just because an operation is non-concurrent, does not mean it cannot be executed concurrently, it simply means that you don't have to handle the concurrency yourself.)

If you need more control over threading and the run-time environment of your operations, you can make use of concurrent operations. To do this, you subclass NSOperation and override the start method. In the start method, you can spawn threads and setup the environment before calling the main method. You are also required to maintain the state of the NSOperation by setting properties like isExecuting and isFinished. In short, concurrent operations give you a lot more control, but also demand more effort—for most tasks non-concurrent operations suffice.


There's no reason you can't create the context in main() for a concurrent queue, but since you have to manage a run loop in main it's usually nicer looking to set up things like a context in start() if you are using that technique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜