gpt4 book ai didi

objective-c - NSInvocationOperation 和 NSOperationQueue 并发

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:25 25 4
gpt4 key购买 nike

我在 iOS5 中使用 NSInvocationOperationNSOperationQueue 开发。根据关于调用对象的苹果文档:

The NSInvocationOperation class is a concrete subclass of NSOperation... This class implements a non-concurrent operation.

好的,那么我的 NSInvocationOperation 对象是同步执行的吗? (在这里纠正我)Apple 的文档还提到了操作队列对象:

In iOS, operation queues do not use Grand Central Dispatch to execute operations. They create separate threads for non-concurrent operations and launch concurrent operations from the current thread.

我正在使用 NSInvocationObject,这是一个非并发对象,并将其添加到操作队列中,如下所示:

[operationQueue addOperation:operation];

所以我的问题是:1) 由于操作队列将产生一个单独的线程来执行 NSInvocationObject,正如它在文档中所说的那样,它会异步运行而不是同步运行吗?

[更新 - 回应 Dani 在下方的回答。取自 Apple link .

NSOperation and NSOperationQueue

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.

最佳答案

如果将它添加到操作队列中,它将相对于您的其余代码异步运行,但在操作队列中同步运行。这很像:

With synchronous objects:Creating thread    |    |\    | \______    |        |    |       Operation A    |        |    |       Operation B    |        |    |        |With asynchronous objects:Creating thread    |    |\    | \___________________    |                     |    |\                  Operation A    | \______             |    |        |            |    |       Operation B   |    |        |            |    |        |            |

关于objective-c - NSInvocationOperation 和 NSOperationQueue 并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8454137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com