簡(jiǎn)述
NSOperation是對(duì)GCD的包裝
兩個(gè)核心概念【隊(duì)列+操作】
01 NSOperation本身是抽象類,只能使用它的子類
02 三個(gè)子類分別是:
1、NSInvocationOperation
2、NSBlockOperation
03 NSOperation和NSOperationQueue結(jié)合使用實(shí)現(xiàn)多線程并發(fā)
代碼
-
NSInvocationOperation基本使用
-(void)demo1{ //1.封裝操作 /* 第一個(gè)參數(shù):目標(biāo)對(duì)象 第二個(gè)參數(shù):該操作要調(diào)用的方法,最多接受一個(gè)參數(shù) 第三個(gè)參數(shù):調(diào)用方法傳遞的參數(shù),如果方法不接受參數(shù),那么該值傳nil */ NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil]; //2.啟動(dòng)操作 [operation start]; }
補(bǔ)充:只要執(zhí)行操作,就會(huì)調(diào)用
target
的run
方法,,但是執(zhí)行的結(jié)果默認(rèn)為主線程調(diào)用(這里的話我就不上圖了),只有添加到NSOperationQueue
中才會(huì)開啟新的線程,沒有添加到NSOperationQueue
中,都是同步執(zhí)行,后面會(huì)介紹NSOperationQueue
,如何實(shí)現(xiàn)異步執(zhí)行 -
NSBlockOperation基本使用
-(void)demo2{ NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ //在主線程中執(zhí)行 NSLog(@"---LitterL_1--%@",[NSThread currentThread]); }]; //2.追加操作,追加的操作在子線程中執(zhí)行 [operation addExecutionBlock:^{ NSLog(@"---LitterL_2--%@",[NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"---LitterL_3--%@",[NSThread currentThread]); }]; //3.啟動(dòng)執(zhí)行操作 [operation start]; }
補(bǔ)充:只要`NSBlockOperation`封裝的操作數(shù) > 1,就會(huì)異步執(zhí)行操作
-
NSOperationQueue基本使用
在上面子類中演示了調(diào)用start
方法執(zhí)行任務(wù)都是默認(rèn)同步執(zhí)行的,除了NSBlockOperation
封裝的操作數(shù) > 1以外,在這里的話我們就將任務(wù)添加到隊(duì)列中,去看看它是如何異步執(zhí)行;
NSOperation中是有兩種隊(duì)列
01 主隊(duì)列 通過(guò)mainQueue獲得,凡是放到主隊(duì)列中的任務(wù)都將在主線程執(zhí)行
02 非主隊(duì)列 直接alloc init出來(lái)的隊(duì)列。非主隊(duì)列同時(shí)具備了并發(fā)和串行的功能,通過(guò)設(shè)置最大并發(fā)數(shù)屬性來(lái)控制任務(wù)是并發(fā)執(zhí)行還是串行執(zhí)行
代碼:
-(void)demo3{
//1.創(chuàng)建隊(duì)列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//2.封裝操作
NSInvocationOperation *op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"2----%@",[NSThread currentThread]);
}];
[op2 addExecutionBlock:^{
NSLog(@"3----%@",[NSThread currentThread]);
}];
//3、添加到隊(duì)列中去
[queue addOperation:op1];
[queue addOperation:op2];
//4、補(bǔ)充:簡(jiǎn)便方法
[queue addOperationWithBlock:^{
NSLog(@"4----%@",[NSThread currentThread]);
}];
}
-(void)download{
NSLog(@"1----%@",[NSThread currentThread]);
}
結(jié)束
本章到此結(jié)束
歡迎各位碼友隨意轉(zhuǎn)載并指正