题目如下:
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"4");
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"5");
});
[self performSelector:@selector(test2)];
[self performSelector:@selector(test3) withObject:nil afterDelay:0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSLog(@"6");
});
[self test1];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)test1{
NSLog(@"1");
}
- (void)test2{
NSLog(@"2");
}
- (void)test3{
NSLog(@"3");
}
求执行顺序:
分析:
1、[self performSelector:@selector(test2)];和 [self test1]; 都是在主线程中执行的所以 2 在1 前。
2、然后 NSLog(@"6"); 是在异步线程中只要在2之后随便一个位置都可以(应该在1之后、视执行速度而定)
3、分析 [self performSelector:@selector(test3) withObject:nil afterDelay:0]; 这个方法是异步方法,只能在主线程中调用故在2 1 之后
4、4 和 5 都是需要获取主线程然后在主线程中执行。最快在输出 2 1 3 之后执行;最慢在输出2 1 3后的时间再加上一次runloop时间执行
故顺序为 2 1 3 4 5 。6可以插入在2之后的任意位置。