这可能是一个愚蠢的问题,但我需要自己问清楚。
要将块提交到队列中执行,请使用函数dispatch_sync
和dispatch_async
。它们都将队列和块作为参数。dispatch_async
立即返回,异步运行块,同时dispatch_sync
阻止执行,直到提供的块返回。以下是一些情况:
情况一
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
[self goDoSomethingLongAndInvolved];
dispatch_async(queue, ^{
NSLog(@"this is statement1");
});
});
情况2
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_sync(queue, ^{
[self goDoSomethingLongAndInvolved];
dispatch_sync(queue, ^{
NSLog(@"this is statement1");
});
});
情况 3
{
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
[self goDoSomethingLongAndInvolved];
dispatch_sync(queue, ^{
NSLog(@"this is statement1");
});
});
情况4
{
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_sync(queue, ^{
[self goDoSomethingLongAndInvolved];
dispatch_async(queue, ^{
NSLog(@"this is statement1");
});
});
}
并且goDoSomethingLongAndInvolved
是
-(void)goDoSomethingLongAndInvolved {
NSLog(@"goDoSomethingLongAndInvolved");
}
我试图在 Xcode 中运行它们,但我根本看不出有什么区别。
所以我的问题是:
- 这些情况之间的主要区别是什么?
- 如果我用 替换
queue
怎么dispatch_get_main_queue()
办?