代碼塊和并發(fā)性
標簽: OC學習
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'>實現(xiàn)方式:</font>
<returntype> (^blockname)(list of arguments) = ^(arguments){ body; };
返回類型,參數(shù)表都是可以省略的部分,如下例一個極簡代碼塊:
void (^theBlock)() = ^{ printf("Hello World\n"); };
1.2 代碼塊的使用
- 同一般函數(shù)直接通過函數(shù)名調(diào)用;
- 直接將代碼塊當做參數(shù);
2.并發(fā)性
核心方法:GCD
2.1 NSObject提供的方法
performSelectorInBackground:withObject:能夠創(chuàng)建一個線程在后臺運行方法;
限制:
- 必須創(chuàng)建自動釋放池
- 方法不能有返回值,至多有一個參數(shù)
示例:
//方法函數(shù)定義
-(void) myBackgroundMethod:(id)myObject
{
@autoreleasepool
{
NSLog(@"My background method %@",myObject);
}
}
//方法調(diào)用
[self performSelectorInBackground:@selector(myBackgroundMethod) withObject:argumentObject];
2.2 調(diào)度隊列
使用方法: 實現(xiàn)方法代碼,然后為其指派一個隊列
- 連續(xù)隊列
- 并發(fā)隊列
- 主隊列
1)連續(xù)隊列:一連串任務按照一定順序執(zhí)行,先入先出;
//第一個參數(shù)為隊列名稱,第二個參數(shù)為隊列特性
dispatch_queue-t myQueue;
myQueue = dispatch_queue_create("queueName",NULL);
2)并發(fā)隊列:系統(tǒng)提供3種:高優(yōu)先級,默認優(yōu)先級,低優(yōu)先級,
dispatch_queue-t myQueue;
myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
3)主隊列:使用dispatch_get_main_queue可以訪問與應用程序主線程有關的連續(xù)隊列;
dispatch_queue-t myQueue;
myQueue = dispatch_get_current_queue(void);