将块分配到主队列通常是从后台队列完成的,以表示某些后台处理已经完成.
- (void)doCalculation
{
//you can use any string instead "com.mycompany.myqueue"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
int result = <some really long calculation that takes seconds to complete>;
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUIWithResult:result];
});
});
}
在本例中,我们在后台队列上执行冗长的计算,并且需要在计算完成后更新我们的UI.更新UI通常必须从主队列完成,所以我们使用第二个嵌套的DISPATCH_Async‘发信号’回主队列.
可能还有其他一些示例,其中您可能希望分派回主队列,但通常是以这种方式完成的,即从分派到后台队列的块中嵌套.
- background processing finished -> update UI
- chunk of data processed on background queue -> signal main queue to start next chunk
- incoming network data on background queue -> signal main queue that message has arrived
- 等,等等
至于你为什么要把主队调度到主队...通常情况下,您不会这样做,尽管可以想象,您这样做是为了在运行循环的下一次安排一些工作.