1.一次性代码(多用于单例)
1>只执行一次,创建了到销毁都只会执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"once");
});
2.延迟执行
1>关于延迟执行,有三种方式可以实现
a.performSelector
b.定时器
c.
gcd
// 1.延迟执行的第一种方法
[self performSelector:@selector(task) withObject:nil afterDelay:2.0];
// 2.延迟执行的第二种方法
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
// 3.延迟执行的第三种方法
/** 第一个参数:DISPATCH_TIME_NOW 从现在开始计算事件
第二个参数:延迟的时间 GCD时间单位:那秒
第叁个参数:队列
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"GCD ---- %@",[NSThread currentThread]);
});
3.栅栏函数
作用:只有当栅栏函数执行完毕后才能执行后面的函数
需求:使用栅栏函数规定线程执行顺序
注意:栅栏函数不能使用全局并发队列(否则没有意义)
dispatch_queue_t queue = dispatch_queue_create("download", DISPATCH_QUEUE_CONCURRENT);
//1.异步函数
dispatch_async(queue, ^{ for (NSInteger i =0 ; i < 5 ; i++){
NSLog(@"task1 -- %zd -- %@",i,[NSThread currentThread]);
} });
dispatch_async(queue, ^{ for (NSInteger i =0 ; i < 5 ; i++){
NSLog(@"task2 -- %zd -- %@",i,[NSThread currentThread]);
} });
dispatch_barrier_async(queue, ^{
NSLog(@"+++++++++++++++");
});
dispatch_async(queue, ^{ for (NSInteger i =0 ; i < 5 ; i++){
NSLog(@"task3 -- %zd -- %@",i,[NSThread currentThread]);
} });
dispatch_barrier_async(queue, ^{
NSLog(@"+++++++++++++++");
});
dispatch_async(queue, ^{ for (NSInteger i =0 ; i < 5 ; i++){
NSLog(@"task4 -- %zd -- %@",i,[NSThread currentThread]);
} });