GCD讲解与异步下载图片例子

2017-08-18  本文已影响27人  猪队友小L

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_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

第二个参数flags

异步下载图片

- (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];
            }
        });
    });
}
上一篇下一篇

猜你喜欢

热点阅读