常用的GCD

在开发中经常遇到执行一些耗时任务后如加载网络资源,需要回到主线程中更新UI界面:

切记: 刷新UI必须在主线程里进行,否则项目会崩溃


在主线程的任意方法中加入:  

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  

// 执行耗时的异步操作(例如图片的加载或者上传下载之类的)...  

dispatch_async(dispatch_get_main_queue(), ^{  

// 回到主线程,执行UI刷新操作  

});

});


iOS常见的延时执行有2种方式

调用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秒后异步执行这里的代码...

});


使用dispatch_once函数能保证某段代码在程序运行过程中只被执行1次(在单列模式中用到)

static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{  

// 只执行1次的代码(这里面默认是线程安全的)

});


GCD还有一种很好用得一种用法:队列组

有这么1种需求 
首先:分别异步执行N个耗时的操作 
其次:等N个异步操作都执行完毕后,再回到主线程执行操作


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(), ^{  

// 等前面的异步操作都执行完毕后,回到主线程...

});



// 后台执行:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
  // something
});
 
// 主线程执行:
dispatch_async(dispatch_get_main_queue(), ^{
  // something
});
 
// 一次性执行:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
  // code to be executed once
});
 
// 延迟2秒执行:
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^( void ){
  // code to be executed on the main queue after delay
});
 
// 自定义dispatch_queue_t
dispatch_queue_t urls_queue = dispatch_queue_create( "blog.devtang.com" , NULL);
dispatch_async(urls_queue, ^{
    // your code
});
dispatch_release(urls_queue);
 
// 合并汇总结果
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
  // 并行执行的线程一
});
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
  // 并行执行的线程二
});
dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
  // 汇总结果
});



猜你喜欢

转载自blog.csdn.net/mr_tangit/article/details/80613448
gcd
今日推荐