问题描述
我是ios开发的新手.我有以下问题:
I am new in ios development. I have following questions:
- 何时使用GCD(dispatch_group_async,dispatch_async(dispatch_get_main_queue()...)以及何时使用performSelectorInBackground/performSelectorOnMainThread?
-
这两者之间有什么区别.
- When we use GCD(dispatch_group_async, dispatch_async(dispatch_get_main_queue()...) and when we use performSelectorInBackground/performSelectorOnMainThread?
What's the differences between those two.
我知道当我们使用performSelectorInBackground时,我们会创建一个新的NSThread.但是当我们使用dispatch_group_async时不一样吗?因为如果我们创建一个以上的dispatch_group_async,则意味着我们需要在队列中提交多个以上的块.这些块可能在不同的队列上运行.因此,当我们创建一个以上的dispatch_group_async时,是否意味着我们创建了一个新线程? (因为块可能在不同的队列上运行)(我对NSThread和块队列感到困惑.....)
I know when we use performSelectorInBackground, we create a new NSThread. But isn't the same when we use dispatch_group_async? Because if we create more than one dispatch_group_async, it means we need to submit more than one blocks in queue. And those blocks might run on different queues. Therefore, when we create more than one dispatch_group_async, does it means we create a new thread? (because blocks may run on different queues) (I kind of confused about NSThread and block queue.....)
谢谢!
推荐答案
何时使用performSelectorInBackground:
从不.不要使用此方法.它产生无限数量的线程.甚至在GCD可用之前,这都是一种可怕的方法.
When to use performSelectorInBackground:
Never. Do not use this method. It spawns an unbounded number of threads. Even before GCD was available, this was a horrible method.
嗯……从不,只是因为不方便.这种方法没有什么大不了的.它不如dispatch_async()
有用.
Meh… Never, but just because it's inconvenient. There's nothing deeply wrong with this method. It's just not as useful as dispatch_async()
.
GCD与旧的performSelector…
方法(通常是NSThread
)之间的区别在于,GCD为您管理线程池.通常,应避免在Cocoa中进行手动穿线.而是使用NSOperationQueue
或GCD(dispatch
方法).它们提供了更有用的队列抽象,而不是强迫您手动管理线程.
The difference between GCD and the old performSelector…
methods (and NSThread
in general) is that GCD manages a thread pool for you. In general, you should avoid manual threading in Cocoa. Instead, use NSOperationQueue
or GCD (dispatch
methods). They provide a more useful queue abstraction rather than forcing you to manually manage threads.
请务必阅读Apple的从线程迁移了解更多信息.
Be sure to read over Apple's Migrating Away from Threads for more info.
这篇关于GCD vs PerformSelectorInBackground/performSelectorOnMainThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!