代碼塊和并發(fā)性
標(biāo)簽: OC學(xué)習(xí)
1.代碼塊
傳統(tǒng)的函數(shù)指針:void (*my_func)(void);
代碼塊的定義:將*
換成^
;
1.1 舉例:
int (^square_block)(int number) =
^(int num){return num*num;};
int result = square_block(6);
printf("Result = %d\n", result);
<font color='green'>實(shí)現(xiàn)方式:</font>
<returntype> (^blockname)(list of arguments) = ^(arguments){ body; };
返回類型,參數(shù)表都是可以省略的部分站故,如下例一個(gè)極簡(jiǎn)代碼塊:
void (^theBlock)() = ^{ printf("Hello World\n"); };
1.2 代碼塊的使用
- 同一般函數(shù)直接通過(guò)函數(shù)名調(diào)用;
- 直接將代碼塊當(dāng)做參數(shù);
2.并發(fā)性
核心方法:GCD
2.1 NSObject提供的方法
performSelectorInBackground:withObject:
能夠創(chuàng)建一個(gè)線程在后臺(tái)運(yùn)行方法降狠;
限制:
- 必須創(chuàng)建自動(dòng)釋放池
- 方法不能有返回值,至多有一個(gè)參數(shù)
示例:
//方法函數(shù)定義
-(void) myBackgroundMethod:(id)myObject
{
@autoreleasepool
{
NSLog(@"My background method %@",myObject);
}
}
//方法調(diào)用
[self performSelectorInBackground:@selector(myBackgroundMethod) withObject:argumentObject];
2.2 調(diào)度隊(duì)列
使用方法:
實(shí)現(xiàn)方法代碼庇楞,然后為其指派一個(gè)隊(duì)列
- 連續(xù)隊(duì)列
- 并發(fā)隊(duì)列
- 主隊(duì)列
1)連續(xù)隊(duì)列:一連串任務(wù)按照一定順序執(zhí)行榜配,先入先出;
//第一個(gè)參數(shù)為隊(duì)列名稱姐刁,第二個(gè)參數(shù)為隊(duì)列特性
dispatch_queue-t myQueue;
myQueue = dispatch_queue_create("queueName",NULL);
2)并發(fā)隊(duì)列:系統(tǒng)提供3種:高優(yōu)先級(jí)
芥牌,默認(rèn)優(yōu)先級(jí)
,低優(yōu)先級(jí)
聂使,
dispatch_queue-t myQueue;
myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
3)主隊(duì)列:使用dispatch_get_main_queue
可以訪問(wèn)與應(yīng)用程序主線程有關(guān)的連續(xù)隊(duì)列壁拉;
dispatch_queue-t myQueue;
myQueue = dispatch_get_current_queue(void);