GCD是什么
CGD就是線程管理,通過dispatch(派發(fā))功能進行操作傍妒,大部分函數(shù)都是C
異步的基本原理
獲取到全局的線程渊鞋,然后扔(dispatch)一段函數(shù)過去,然后處理完畢再獲取到當前線程畜伐,扔(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就是異步派發(fā)
- dispatch_get_global_queue/dispatch_get_main_queue 都是C函數(shù),所以可以直接執(zhí)行
- dispatch_get_global_queue的參數(shù)identifier是指的CPU的優(yōu)先級曹抬,flags截止到iOS9都是保留位溉瓶,無任何意義,必須傳0谤民,不然Return為NULL
- dispatch_get_main_queue即使沒有參數(shù)也得結(jié)尾寫()調(diào)用
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.
*/
在講啥
第一個參數(shù)identifier
- 推薦使用QOS_CLASS_USER_INTERACTIVE等全部通用的全局線程(queue)堰酿,這些都是iOS自己定義的
- 還有就是可以使用CPU里通用的進程優(yōu)先級DISPATCH_QUEUE_PRIORITY_DEFAULT(這里可以去CPU相關(guān)基礎(chǔ)答案)
第二個參數(shù)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];
}
});
});
}