// 1.獲得全局的并發(fā)隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 2.獲得主隊列
dispatch_queue_t queue = dispatch_get_main_queue();
1.下載單張圖片
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSLog(@"--download--%@", [NSThread currentThread]);
// 下載圖片
NSURL *url = [NSURL URLWithString:@"http://news.baidu.com/z/resource/r/image/fanlu.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url]; // 這行會比較耗時
UIImage *image = [UIImage imageWithData:data];
// 回到主線程顯示圖片
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"curThread = %@", [NSThread currentThread]);
self.imageView.image = image;
});
});
2.Group ,group_notify
// 創(chuàng)建一個組
dispatch_group_t group = dispatch_group_create();
// 開啟一個任務(wù)下載圖片1
__block UIImage *image1 = nil;
dispatch_group_async(group, global_queue, ^{
image1 = [self imageWithURL:@"http://news.baidu.com/test01.jpg"];
});
// 開啟一個任務(wù)下載圖片2
__block UIImage *image2 = nil;
dispatch_group_async(group, global_queue, ^{
image2 = [self imageWithURL:@"http://news.baidu.com/z/resource/test02.jpg"];
});
// 同時執(zhí)行下載圖片1\下載圖片2操作
// 等group中的所有任務(wù)都執(zhí)行完畢, 再回到主線程執(zhí)行其他操作
dispatch_group_notify(group, main_queue, ^{
self.imageView1.image = image1;
self.imageView2.image = image2;
// 合并
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 100), NO, 0.0);
[image1 drawInRect:CGRectMake(0, 0, 100, 100)];
[image2 drawInRect:CGRectMake(100, 0, 100, 100)];
self.bigImageView.image = UIGraphicsGetImageFromCurrentImageContext();
// 關(guān)閉上下文
UIGraphicsEndImageContext();
});
3.處理讀者與寫者問題dispatch_barrier_async
1.因為只有并發(fā)隊列才會有不安全的問題, 所以需要自定義并發(fā)隊列來管理:
@property (nonatomic, strong) dispatch_queue_t concurrentPhotoQueue;
2.寫者:
- (void)addPhoto:(Photo *)photo {
if (photo) { // 1
dispatch_barrier_async(self.concurrentPhotoQueue, ^{ // 2
[_photosArray addObject:photo]; // 3
dispatch_async(dispatch_get_main_queue(), ^{ // 4
[self postContentAddedNotification];
});
});
}
}
3.讀者:
- (NSArray *)photos {
__block NSArray *array; // 1
dispatch_sync(
self.concurrentPhotoQueue, ^{ // 2
array = [NSArray arrayWithArray:_photosArray]; // 3
});
return array;
}
4.初始化自定義的并發(fā)隊列:
+ (instancetype)sharedManager {
static PhotoManager *sharedPhotoManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedPhotoManager = [[PhotoManager alloc] init];
sharedPhotoManager->_photosArray = [NSMutableArray array]; // ADD THIS:
sharedPhotoManager->_concurrentPhotoQueue = dispatch_queue_create("com.selander.GooglyPuff.photoQueue", DISPATCH_QUEUE_CONCURRENT); });
return sharedPhotoManager;
}