GCD 上干货 >>>>
不喜欢废话
/// GCD - 异步主线程
/// @param block 回调
NS_INLINE void mo_dispatch_async_main(dispatch_block_t block) {
dispatch_async(dispatch_get_main_queue(), block);
}
/// GCD - 异步线程
/// @param block 回调
NS_INLINE void mo_dispatch_async(dispatch_block_t block) {
dispatch_async(dispatch_get_global_queue(0, 0), block);
}
/// GCD - 同步线程
/// @param block 回调
NS_INLINE void mo_dispatch_sync(dispatch_block_t block) {
dispatch_async(dispatch_get_global_queue(0, 0), block);
}
/// GCD - 异步列队
/// @param group 列队
/// @param block 回调
NS_INLINE void mo_dispatch_group_async(dispatch_group_t group, dispatch_block_t block) {
dispatch_group_async(group, dispatch_get_global_queue(0, 0), block);
}
/// GCD - 异步列队通知
/// @param group 列队
/// @param block 回调
NS_INLINE void mo_dispatch_group_notify(dispatch_group_t group, dispatch_block_t block) {
dispatch_group_notify(group, dispatch_get_main_queue(), block);
}
/// GCD - 迟延执行
/// @param time 迟延时间,单位:秒
/// @param block 回调
NS_INLINE void mo_dispatch_after(int64_t time, dispatch_block_t block) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}
重点说下异步列队:
需求: 当N个方法执行完成后,在执行一个统计方法;
注意: 列队和通知的'group'必须是一个指针变量,否则通知比列队结果先执行.
下边干货⬇️
NSLog(@"主线程: %@",[NSThread currentThread]);
NSLog(@"上边的代码");
__block int i = 0;
dispatch_group_t group = dispatch_group_create();
NSLog(@"异步1: %d", i);
mo_dispatch_group_async(group, ^{
[NSThread sleepForTimeInterval:7];
NSLog(@"结束1: %@",[NSThread currentThread]);
i += 7;
});
NSLog(@"异步2: %d", i);
mo_dispatch_group_async(group, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"结束2: %@",[NSThread currentThread]);
i += 2;
});
NSLog(@"异步3: %d", i);
mo_dispatch_group_async(group, ^{
[NSThread sleepForTimeInterval:5];
NSLog(@"结束3: %@",[NSThread currentThread]);
i += 5;
});
mo_dispatch_group_notify(group, ^{
NSLog(@"统计 >>> : %d", i);
});
NSLog(@"下边的代码: %d", i);
log:
2020-03-17 13:48:30.694475+0800 DomeOC[3404:117078] 主线程: <NSThread: 0x600000f1c5c0>{number = 1, name = main}
2020-03-17 13:48:30.694590+0800 DomeOC[3404:117078] 上边的代码
2020-03-17 13:48:30.694682+0800 DomeOC[3404:117078] 异步1: 0
2020-03-17 13:48:30.694824+0800 DomeOC[3404:117078] 异步2: 0
2020-03-17 13:48:30.694941+0800 DomeOC[3404:117078] 异步3: 0
2020-03-17 13:48:30.695048+0800 DomeOC[3404:117078] 下边的代码: 0
2020-03-17 13:48:32.695903+0800 DomeOC[3404:117151] 结束2: <NSThread: 0x600000f4f240>{number = 4, name = (null)}
2020-03-17 13:48:35.696959+0800 DomeOC[3404:117149] 结束3: <NSThread: 0x600000f7b540>{number = 7, name = (null)}
2020-03-17 13:48:37.698527+0800 DomeOC[3404:117155] 结束1: <NSThread: 0x600000f44bc0>{number = 5, name = (null)}
2020-03-17 13:48:37.698971+0800 DomeOC[3404:117078] 统计 >>> : 14