GCD基本使用
//一、线程间通信:从子线程回到主线程 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async( queue, ^{ // 执⾏耗时的异步操作... dispatch_async(dispatch_get_main_queue(), ^{ // 回到主线程,执⾏UI刷新操作 }); });
二、延迟执行:iOS常见的延时执行有2种方式
(1)调用NSObject的方法
[self performSelector:@selector(test) withObject:nil afterDelay:2.0];
// 2秒后再调用self的run方法
(2)使用GCD函数
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 2秒后异步执行这里的代码...
});
//第一种方法:延迟调用,该方法在那个线程调用,那么run就在哪个线程执行(当前线程),通常是主线程。 - (void)use2 { NSLog(@"主线程:%@",[NSThread mainThread]); dispatch_queue_t queue= dispatch_queue_create("wendingding", NULL); dispatch_async(queue, ^{ NSLog(@"新建:%@",[NSThread currentThread]); [self performSelector:@selector(test) withObject:nil afterDelay:3]; //此行没用调用
}); [self performSelector:@selector(test) withObject:nil afterDelay:3]; } - (void)test { NSLog(@"延迟线程:%@",[NSThread currentThread]); }
打印:
//延迟调用2 - GCD - (void)use3 { NSLog(@"当前线程:%@",[NSThread currentThread]); //主队列 dispatch_queue_t queue = dispatch_get_main_queue(); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), queue, ^{ NSLog(@"延迟线程:%@",[NSThread currentThread]); }); //并发队列 dispatch_queue_t queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), queue2, ^{ NSLog(@"并发队列:%@",[NSThread currentThread]); }); }
三、使用dispatch_once一次性代码
使用dispatch_once函数能保证某段代码在程序运行过程中只被执行1次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 只执行1次的代码(这里面默认是线程安全的)
});
整个程序运行过程中,只会执行一次。
//单例模式
#import "Cliet.h" static Cliet *singleClient = nil; @implementation Cliet + (instancetype)shareClient { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ singleClient = [[Cliet alloc] init]; }); return singleClient; }
使用时直接输入dispatch_once即可,如下:
轻击即可创建如下形式,很方便:
static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ });
四、队列组
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(), ^{ // 等前面的异步操作都执行完毕后,回到主线程... });
参考地址:文顶顶微博 http://www.cnblogs.com/wendingding/p/3807716.html