NSOperation 与 Grand Central Dispatch [英] NSOperation vs Grand Central Dispatch

查看:18
本文介绍了NSOperation 与 Grand Central Dispatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 iOS 的并发编程.到目前为止,我已经阅读了关于 NSOperation/NSOperationQueueGCD.使用 NSOperationQueue 而不是 GCD 反之亦然的原因是什么?

I'm learning about concurrent programming for iOS. So far I've read about NSOperation/NSOperationQueue and GCD. What are the reasons for using NSOperationQueue over GCD and vice versa?

听起来像 GCDNSOperationQueue 从用户那里抽象出 NSThreads 的显式创建.然而,我不清楚这两种方法之间的关系,所以任何反馈都值得赞赏!

Sounds like both GCD and NSOperationQueue abstract away the explicit creation of NSThreads from the user. However the relationship between the two approaches isn't clear to me so any feedback to appreciated!

推荐答案

GCD 是一个基于 C 的低级 API,可以非常简单地使用基于任务的并发模型.NSOperationNSOperationQueue 是做类似事情的 Objective-C 类.NSOperation 首先被引入,但从 10.5iOS 2、NSOperationQueue 和朋友们内部使用GCD 实现.

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

一般来说,您应该使用适合您需要的最高抽象级别.这意味着你通常应该使用 NSOperationQueue 而不是 GCD,除非你需要做一些 NSOperationQueue 不支持的事情.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

请注意,NSOperationQueue 不是 GCD 的简化版";事实上,有很多事情你可以用 NSOperationQueue 非常简单地做,而纯 GCD 需要做很多工作.(示例:带宽受限的队列,一次只运行 N 个操作;在操作之间建立依赖关系.使用 NSOperation 都非常简单,使用 GCD 非常困难.)Apple 完成了努力利用 GCD 创建一个非常好的对象友好的 API 和 NSOperation.除非您有理由不这样做,否则请利用他们的工作.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

警告:另一方面,如果您真的只需要发送一个块,并且不需要 NSOperationQueue 提供的任何附加功能,那么使用 GCD 没有任何问题.只要确保它是适合这项工作的工具即可.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

这篇关于NSOperation 与 Grand Central Dispatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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