GCD总结(三)
4月11日 GCD總結(三)
一、用 GCD 將任務分組
?GCD讓我們創建組,這些組允許你把任務放到一個位置,然后全部運行,運行結束后
會從 GCD 收到一個通知。這一點有很多有價值的用途。例如,假設你有一個 UI-Base APP,想在 UI 上重新加載組件。你有一個表格視圖,一個滾動視圖,一個圖片視圖,就要 用這些方法加載這些組建的內容.
在?GCD?中使用組的時候你應該知道?4?個函數:
dispatch_group_create
創建一個組句柄。一旦你使用完了這個組句柄,應該使用?dispatch_release?函數將其釋 放。
dispatch_group_async
在一個組內提交一個代碼塊來執行。必須明確這個代碼塊屬于哪個組,必須在哪個派送隊列上執行。
dispatch_group_notify
允許你提交一個?Block Object。一旦添加到這個組的任務完成執行之后,這個?Block Object?應該被執行。這個函數也允許你明確執行?Block Object?的分派隊列。
dispatch_release這個函數釋放那任何一個你通過?dispatch_group_create?函數創建的分派小組。
1、dispatch_group_async
?
//
? ? dispatch_group_t taskGroup=dispatch_group_create();
? ? dispatch_queue_t mainQueue1=dispatch_get_main_queue();
? ? //reload the table view on the main queue
? ? dispatch_group_async(taskGroup, mainQueue1, ^{
? ? ? ?
? ? ? ? //method 1
? ? ? ? NSLog(@"method1-----");
?? ? ? ?
? ? });
?? ?
? ? dispatch_group_async(taskGroup, mainQueue1, ^{
?? ? ? ?
? ? ? ? //method 2
? ? ? ? NSLog(@"method2----");
? ? });
?? ?
? ? //at the end? when we are done,dispatch the following block
? ? dispatch_group_notify(taskGroup, mainQueue1, ^{
?? ? ? ?
? ? ? ? NSLog(@"finished");
? ? ? ? [[[UIAlertView alloc] initWithTitle:@"Finished"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? message:@"All tasks are finished" delegate:nil
? ? ? ? ? ? ? ? ? ? ? ? ? cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
? ? });
?? ?
? ? //we are done with the group
? ? dispatch_release(taskGroup);
2、也可以分派異步的 C 函數到一個分派組來使用 dispatch_group_async_f 函數
?dispatch_group_t taskGroup = dispatch_group_create();?
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_group_async_f(taskGroup, mainQueue,
(__bridge void *)self, reloadAllComponents);
/* At the end when we are done, dispatch the following block */ dispatch_group_notify(taskGroup, mainQueue, ^{
/* Do some processing here */[[[UIAlertView alloc] initWithTitle:@"Finished"
});
/* We are done with the group */?
dispatch_release(taskGroup);
二、用 GCD 構建自己的分派隊列
?利用?GCD,你可以創建你自己的串行分派隊列,串行調度隊列按照先入先出(FIFO)的原則運行它們的任務。然而,串行隊列上的異步任務不會在主 線程上執行,這就使得串行隊列極需要并發 FIFO 任務。所有提交到一個串行隊列的同步 任務會在當前線程上執行,在任何可能的情況下這個線程會被提交任務的代碼使用。但是提 交到串行隊列的異步任務總是在主線程以外的線程上執行
?
| dispatch_queue_t firstSerialQueue = dispatch_queue_create("com.pixolity.GCD.serialQueue1", 0); dispatch_async(firstSerialQueue, ^{ NSUInteger counter = 0; |
| for (counter = 0; counter < 5; counter++){ NSLog(@"First iteration, counter = %lu", (unsigned long)counter); } }); dispatch_async(firstSerialQueue, ^{ NSUInteger counter = 0; for (counter = 0; counter < 5; counter++){NSLog(@"Second iteration, counter = %lu", (unsigned long)counter); } }); dispatch_async(firstSerialQueue, ^{ NSUInteger counter = 0;for (counter = 0; counter < 5; counter++){NSLog(@"Third iteration, counter = %lu", (unsigned long)counter); } }); dispatch_release(firstSerialQueue); |
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: XML的四种解析器(dom,sax,jd
- 下一篇: 如何让网页背景图片完整显示