当前位置: 代码迷 >> 综合 >> 面试必看 iOS多线程GCD(3)
  详细解决方案

面试必看 iOS多线程GCD(3)

热度:54   发布时间:2024-01-28 15:35:28.0

延时执行

? iOS常见的延时执行

调用NSObject的方法

[self performSelector:@selector(run) withObject:nil afterDelay:2.0];

// 2秒后再调用self的run方法

 

使用GCD函数

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{// 2秒后执行这里的代码...
});

使用NSTimer

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:NO];

一次性代码

? 使用dispatch_once函数能保证某段代码在程序运行过程中只被执行1次

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{// 只执行1次的代码(这里面默认是线程安全的)
});

快速迭代

 ? 使用dispatch_apply函数能进行快速迭代遍历

dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t index){// 执行10次代码,index顺序不确定
});

队列组

? 有这么1种需求

首先:分别异步执行2个耗时的操作
其次:等2个异步操作都执行完毕后,再回到主线程执行操作

? 如果想要快速高效地实现上述需求,可以考虑用队列组

dispatch_group_t group =  dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// 执行1个耗时的异步操作
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// 执行1个耗时的异步操作
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{// 等前面的异步操作都执行完毕后,回到主线程...
});

 

 

 

  相关解决方案