GCD是什么
CGD就是线程管理,通过dispatch(派发)功能进行操作,大部分函数都是C
异步的基本原理
获取到全局的线程,然后扔(dispatch)一段函数过去,然后处理完毕再获取到当前线程,扔(dispatch)回来。
代码
//dispatch_get_global_queue(long identifier, unsigned long flags) 全局线程
//dispatch_get_main_queue(void) 主线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//被扔到全局的代码段
dispatch_async(dispatch_get_main_queue(), ^{
//被扔回主线程的代码段
});
});
代码讲解
- dispatch_async就是异步派发
- dispatch_get_global_queue/dispatch_get_main_queue 都是C函数,所以可以直接执行
- dispatch_get_global_queue的参数identifier是指的CPU的优先级,flags截止到iOS9都是保留位,无任何意义,必须传0,不然Return为NULL
- dispatch_get_main_queue即使没有参数也得结尾写()调用
dispatch_get_global_queue讲解
先上原文
/*!
* @function dispatch_get_global_queue
*
* @abstract
* Returns a well-known global concurrent queue of a given quality of service
* class.
*
* @discussion
* The well-known global concurrent queues may not be modified. Calls to
* dispatch_suspend(), dispatch_resume(), dispatch_set_context(), etc., will
* have no effect when used with queues returned by this function.
*
* @param identifier
* A quality of service class defined in qos_class_t or a priority defined in
* dispatch_queue_priority_t.
*
* It is recommended to use quality of service class values to identify the
* well-known global concurrent queues:
* - QOS_CLASS_USER_INTERACTIVE
* - QOS_CLASS_USER_INITIATED
* - QOS_CLASS_DEFAULT
* - QOS_CLASS_UTILITY
* - QOS_CLASS_BACKGROUND
*
* The global concurrent queues may still be identified by their priority,
* which map to the following QOS classes:
* - DISPATCH_QUEUE_PRIORITY_HIGH: QOS_CLASS_USER_INITIATED
* - DISPATCH_QUEUE_PRIORITY_DEFAULT: QOS_CLASS_DEFAULT
* - DISPATCH_QUEUE_PRIORITY_LOW: QOS_CLASS_UTILITY
* - DISPATCH_QUEUE_PRIORITY_BACKGROUND: QOS_CLASS_BACKGROUND
*
* @param flags
* Reserved for future use. Passing any value other than zero may result in
* a NULL return value.
*
* @result
* Returns the requested global queue or NULL if the requested global queue
* does not exist.
*/
在讲啥
第一个参数identifier
- 推荐使用QOS_CLASS_USER_INTERACTIVE等全部通用的全局线程(queue),这些都是iOS自己定义的
- 还有就是可以使用CPU里通用的进程优先级DISPATCH_QUEUE_PRIORITY_DEFAULT(这里可以去CPU相关基础答案)
第二个参数flags
- flags不要乱写,写了就真立flag了,传入0就好
- flags不是0就返回NULL,是0就会返回请求的global queue
异步下载图片
- (void)downloadHeadImgAsyncToImageView:(nullable UIImageView *)headImgView {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *urlString = @"http://";
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *headImg = nil;
if (data != nil && ![urlString isEqualToString:@""]) {
headImg = [UIImage imageWithData:data];
}
dispatch_async(dispatch_get_main_queue(), ^{
if (headImgView) {
[headImgView setImage:headImg];
}
});
});
}
网友评论