dispatch_get_main_queue 块内的代码
code inside dispatch_get_main_queue block
我有几个像下面这样的代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"1");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"3");
});
NSLog(@"2");
}
在控制台中,控制台输出为:1, 2, 3
。一开始以为应该是1, 3, 2
因为dispatch_get_main_queue
是主队列,外面也是主队列。为什么输出不同?
你使用 dispatch_async 调度 NSLog(3) 中的代码,这将使其在当前同步函数完成后异步执行。
我建议阅读一般线程和 GCD 的教程,因为它不能并且不应该完全涵盖这一点。
dispatch_async
表示 "submit this block to run on the designated queue when that queue is capable of doing so, but don't block the current thread waiting for the dispatched block to finish, but rather immediately carry on." 而由于 viewDidLoad
在主线程上是 运行,主线程将完成 运行 viewDidLoad
在它到达 运行 您异步分派到主队列的块之前。
我有几个像下面这样的代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"1");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"3");
});
NSLog(@"2");
}
在控制台中,控制台输出为:1, 2, 3
。一开始以为应该是1, 3, 2
因为dispatch_get_main_queue
是主队列,外面也是主队列。为什么输出不同?
你使用 dispatch_async 调度 NSLog(3) 中的代码,这将使其在当前同步函数完成后异步执行。
我建议阅读一般线程和 GCD 的教程,因为它不能并且不应该完全涵盖这一点。
dispatch_async
表示 "submit this block to run on the designated queue when that queue is capable of doing so, but don't block the current thread waiting for the dispatched block to finish, but rather immediately carry on." 而由于 viewDidLoad
在主线程上是 运行,主线程将完成 运行 viewDidLoad
在它到达 运行 您异步分派到主队列的块之前。