1.gcd柵欄函數
2.gcd快速迭代方法(dispatch_apply)同for循環做比較。
案例:將文件夾from中的內容剪切到文件夾to中。
//案例(gcd快速迭代)創建子線程的方法
-(void)movefilegcd{
//拿到文件目錄
NSString* from =@"/Users/wuyanan/Desktop/from";
//獲得目標文件路徑
NSString* to =@"/Users/wuyanan/Desktop/to";
//得到目錄下的所有文件(返回的是數組)
NSArray* subPath = [[NSFileManagerdefaultManager]subpathsAtPath:from];
NSLog(@"wenjian----%@",subPath);
//遍歷所有文件,執行剪切操作
NSIntegercount =[subPathcount];
dispatch_apply(count,dispatch_get_global_queue(0,0), ^(size_tindex) {
//4.1拼接文件的全路徑
//拼接的時候會自動添加/
NSString*fullpath =[fromstringByAppendingPathComponent:subPath[index]];
NSString* tofullpath =[tostringByAppendingPathComponent:subPath[index]];
NSLog(@"wenjian----%@",fullpath);
//4.2執行剪切操作
/*
第一個參數:源文件路徑,要剪切的文件的地址
第二個參數:目標文件路徑,文件應該被放到的位置
第三個參數:
*/
[[NSFileManagerdefaultManager]moveItemAtPath:fullpathtoPath:tofullpatherror:nil];
});
}
注意點:
3.gcd隊列組
gcd的隊列組也可以控制順序。隊列組里面的隊列任務的執行情況。當任務都完成的時候發送通知。
案例2:下載兩張圖片,下載完成后合成一張圖片
-(void)group3
{
/*
1.下載圖片1開子線程
2.下載圖片2開子線程
3.合成圖片并顯示圖片開子線程
*/
//-1.獲得隊列組
dispatch_group_tgroup =dispatch_group_create();
//0.獲得并發隊列
dispatch_queue_tqueue =dispatch_get_global_queue(0,0);
// 1.下載圖片1開子線程
dispatch_group_async(group, queue,^{
NSLog(@"download1---%@",[NSThreadcurrentThread]);
//1.1確定url
NSURL*url = [NSURLURLWithString:@"http://www.qbaobei.com/tuku/images/13.jpg"];
//1.2下載二進制數據
NSData*imageData = [NSDatadataWithContentsOfURL:url];
//1.3轉換圖片
self.image1= [UIImageimageWithData:imageData];
});
// 2.下載圖片2開子線程
dispatch_group_async(group, queue,^{
NSLog(@"download2---%@",[NSThreadcurrentThread]);
//2.1確定url
NSURL*url = [NSURLURLWithString:@"http://pic1a.nipic.com/2008-09-19/2008919134941443_2.jpg"];
//2.2下載二進制數據
NSData*imageData = [NSDatadataWithContentsOfURL:url];
//2.3轉換圖片
self.image2= [UIImageimageWithData:imageData];
});
//3.合并圖片
//主線程中執行
dispatch_group_notify(group,dispatch_get_main_queue(), ^{
NSLog(@"combie---%@",[NSThreadcurrentThread]);
//3.1創建圖形上下文
UIGraphicsBeginImageContext(CGSizeMake(200,200));
//3.2畫圖1
[self.image1drawInRect:CGRectMake(0,0,200,100)];
self.image1=nil;
//3.3畫圖2
[self.image2drawInRect:CGRectMake(0,100,200,100)];
self.image2=nil;
//3.4根據上下文得到一張圖片
UIImage*image =UIGraphicsGetImageFromCurrentImageContext();
//3.5關閉上下文
UIGraphicsEndImageContext();
//3.6更新UI
//dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"UI----%@",[NSThreadcurrentThread]);
self.imageView.image= image;
//});
});
}
使用creat函數創建的并發隊列和全局隊列的主要區別:
1.使用全局并發隊列在整個應用程序中本身是默認存在的,并且對應有高優先級、默認優先級,低優先級和后臺優先級一共四個并發隊列。我們只是選擇一個直接拿來用。而且create函數是實打實的從頭開始創建一個隊列。
2.在iOS6之前,在gcd中凡是使用了帶有create和retain的函數,最后都需要做一次release操作。而主隊列和全局并發隊列不需要我們手動release。iOS6之后,不需要手動管理。
在使用柵欄函數的時候,蘋果官方規定只有柵欄函數只有在和使用creat函數自己創建的并發隊列一起使用的時候才有效
4.GCD補充
gcd開啟線程的兩種方法比較: