iOS多線程-多線程實(shí)現(xiàn)之NSOperation

  • NSOperation的作用

    • 配合使用NSOperation和NSOperationQueue也能實(shí)現(xiàn)多線程編程
  • 具體實(shí)現(xiàn)步驟

    • 先將需要執(zhí)行的操作封裝到一個(gè)NSOperation對(duì)象中
    • 然后將NSOperation對(duì)象添加到NSOperationQueue中
    • 系統(tǒng)會(huì)自動(dòng)將NSOperationQueue中的NSOperation取出來(lái)
    • 將取出的NSOperation封裝的操作放到一條新線程中執(zhí)行
  • NSOperation是一個(gè)抽象類(lèi),并不具備封裝操作的能力,必須使用其子類(lèi)

  • 使用NSOperation子類(lèi)的方式有三種

    • NSInvocationOperation
    • NSBlockOperation
    • 自定義子類(lèi)繼承NSOperation,實(shí)現(xiàn)內(nèi)部響應(yīng)的方法

廢話不多說(shuō)上代碼

  • NSInvocationOperation單獨(dú)使用
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //創(chuàng)建InvocationOperation 對(duì)象
    //注意: 如果沒(méi)有放入隊(duì)列中的話需要手動(dòng)啟動(dòng)
    //
    /*
     第一個(gè)參數(shù): 目標(biāo)對(duì)象
     第二個(gè)參數(shù): 調(diào)用目標(biāo)對(duì)象的那個(gè)方法
     第三個(gè)參數(shù): 目標(biāo)方法需要傳入的參數(shù), 如果沒(méi)有參數(shù)寫(xiě)nil
     */
    NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationOperation) object:nil];

    //啟動(dòng)任務(wù)
    //默認(rèn)情況下(在沒(méi)有被放入隊(duì)列中時(shí)),調(diào)用start方法,是在當(dāng)前線程下執(zhí)行任務(wù),等任務(wù)執(zhí)行完畢才會(huì)繼續(xù)往下執(zhí)行(會(huì)阻塞當(dāng)前線程).
    //start 底層其實(shí)就是去調(diào)用 main 方法 [operation main]
    [operation start];
}
  • NSInvocationOperation配合NSOperationQueue使用
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //創(chuàng)建NSOperationQueue對(duì)象
    //直接alloc/init手動(dòng)創(chuàng)建的NSOperationQueue對(duì)象,是在子線程中執(zhí)行,默認(rèn)并發(fā)執(zhí)行
    //[NSOperationQueue mainQueue]創(chuàng)建出來(lái)的NSOperationQueue對(duì)象,是在主線程中執(zhí)行
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];

    NSInvocationOperation * invocation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationOperation) object:nil];
    NSInvocationOperation * invocation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationOperation) object:nil];

    //添加到隊(duì)列后,就不需要再手動(dòng)start了
    //異步執(zhí)行
        //注意:如果是主隊(duì)列,并且當(dāng)前線程正好也是主線程的話,會(huì)先執(zhí)行完所有代碼,然后再去執(zhí)行隊(duì)列中的任務(wù)
    [queue addOperation:invocation1];
    [queue addOperation:invocation2];
}
  • NSBlockOperation單獨(dú)使用
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //創(chuàng)建BlockOperation對(duì)象
    //注意: 如果沒(méi)有放入隊(duì)列中的話需要手動(dòng)啟動(dòng)
    NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1==%@",[NSThread currentThread]);
    }];

    //通過(guò)addExecutionBlock方法動(dòng)態(tài)添加多個(gè)任務(wù)
    [operation addExecutionBlock:^{

        NSLog(@"2==%@",[NSThread currentThread]);
    }];

    [operation addExecutionBlock:^{

        NSLog(@"3==%@",[NSThread currentThread]);
    }];

    [operation addExecutionBlock:^{

        NSLog(@"4==%@",[NSThread currentThread]);
    }];
    //啟動(dòng)任務(wù)
    //默認(rèn)情況下(在沒(méi)有被放入隊(duì)列中時(shí)),調(diào)用start方法,會(huì)等所有任務(wù)執(zhí)行完畢才會(huì)繼續(xù)執(zhí)行下去,也就是說(shuō)會(huì)阻塞當(dāng)前線程
    //最先添加的任務(wù)是在當(dāng)前線程中執(zhí)行, 后添加的任務(wù)是在子線程中執(zhí)行
    //start 底層其實(shí)就是去調(diào)用 main 方法 [operation main]
    [operation start];

    NSLog(@"end");
}
  • NSBlockOperation配合NSOperationQueue使用
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //創(chuàng)建NSOperationQueue對(duì)象
    //直接alloc/init手動(dòng)創(chuàng)建的NSOperationQueue對(duì)象,是在子線程中執(zhí)行,默認(rèn)并發(fā)執(zhí)行
    //[NSOperationQueue mainQueue]創(chuàng)建出來(lái)的NSOperationQueue對(duì)象,是在主線程中執(zhí)行
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];

    NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"%@",[NSThread currentThread]);
    }];

    //添加到隊(duì)列后,就不需要再手動(dòng)start了
    //異步執(zhí)行
    //注意:如果是主隊(duì)列,并且當(dāng)前線程正好也是主線程的話,會(huì)先執(zhí)行完所有代碼,然后再去執(zhí)行隊(duì)列中的任務(wù)
    [queue addOperation:operation];

    //直接通過(guò)queue的addOperationWithBlock方法來(lái)添加任務(wù)
    [queue addOperationWithBlock:^{
        NSLog(@"%@",[NSThread currentThread]);
    }];
}
  • 自定義子類(lèi)繼承NSOperation,實(shí)現(xiàn)內(nèi)部響應(yīng)的方法

    • 前面說(shuō)過(guò)執(zhí)行任務(wù)的底層實(shí)現(xiàn)其實(shí)就是調(diào)用NSOperation對(duì)象的main方法.
    • 所有我們只要自定一個(gè)類(lèi)繼承NSOperation,重寫(xiě)main,把任務(wù)代碼編寫(xiě)在面方法中即可.系統(tǒng)自帶的NSInvocationOperation和NSBlockOperation的怎么用,自定義的NSOperation也就怎么用.
#import <Foundation/Foundation.h>

@interface YXOperation : NSOperation
@end

@implementation YXOperation
-(void)main{
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"耗時(shí)操作代碼........");
}
@end


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
 // 創(chuàng)建自定義的NSOperation對(duì)象
    YXOperation * operation1 = [[YXOperation alloc] init];
    YXOperation * operation2 = [[YXOperation alloc] init];
    YXOperation * operation3 = [[YXOperation alloc] init];
    YXOperation * operation4 = [[YXOperation alloc] init];

    //把Operation對(duì)象封裝到數(shù)組中
    NSArray * operationArray = @[operation1,operation2,operation3,operation4];

    NSOperationQueue * queue = [[NSOperationQueue alloc] init];

    //把NSOperation對(duì)象數(shù)組添加到隊(duì)列中
    /*
     第一個(gè)參數(shù): NSOperation 對(duì)象數(shù)組
     第二個(gè)參數(shù): 是否等待所有任務(wù)執(zhí)行完畢,  YES(等待,會(huì)阻塞當(dāng)前線程) NO(不等待)
     */
    [queue addOperations:operationArray waitUntilFinished: NO];

    NSLog(@"end");
}
  • 隊(duì)列的暫停,恢復(fù),取消,最大并發(fā)數(shù)

//按鈕點(diǎn)擊事件
- (IBAction)btnClick:(id)sender {
    //設(shè)置與隊(duì)列當(dāng)前狀態(tài)相反的值
    //執(zhí)行狀態(tài)就暫停,暫停狀態(tài)就恢復(fù)
    //暫停之后,會(huì)把當(dāng)前正在執(zhí)行的任務(wù)執(zhí)行完,然后不再執(zhí)行任務(wù)
    //恢復(fù)之后,會(huì)接著繼續(xù)執(zhí)行沒(méi)有執(zhí)行的任務(wù)
    self.queue.suspended = !self.queue.suspended;

    //取消隊(duì)列中所有的任務(wù)
    //注意: 取消之后就不能再恢復(fù)了,當(dāng)前正在執(zhí)行的任務(wù)不會(huì)被取消,
    //底層其實(shí)就是調(diào)用隊(duì)列中所有NSOperation任務(wù)對(duì)象的cancel方法,可以通過(guò)隊(duì)列的operations屬性獲取隊(duì)列中所有NSOperations對(duì)象(self.queue.operations)
    //開(kāi)發(fā)中,自定義Operation的時(shí)候在重寫(xiě)main方式,做耗時(shí)操作時(shí),在適當(dāng)?shù)奈恢门袛嘤脩羰欠袢∠巳蝿?wù),如果取消了直接return任務(wù)
    //self.queue cancelAllOperations];

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.queue = [[NSOperationQueue alloc] init];

    //最大并發(fā)數(shù):最大同時(shí)執(zhí)行的任務(wù)數(shù)
    // 1.默認(rèn)是-1沒(méi)有限制,由系統(tǒng)自己決定
    // 2.不要設(shè)置為0,設(shè)置為0就不會(huì)執(zhí)行任務(wù)了
    // 3.設(shè)置為1,就可以達(dá)到串行的效果
    self.queue.maxConcurrentOperationCount = 1;

    [self.queue addOperationWithBlock:^{
        NSLog(@"==============================================");
        for(int i = 0 ; i < 10000; i++){
            NSLog(@"%d*****%@", i ,[NSThread currentThread]);
        }

    }];

    [self.queue addOperationWithBlock:^{
        NSLog(@"==============================================");
        for(int i = 0 ; i < 10000; i++){
            NSLog(@"%d*****%@", i ,[NSThread currentThread]);
        }

    }];

    [self.queue addOperationWithBlock:^{
        NSLog(@"==============================================");
        for(int i = 0 ; i < 10000; i++){
            NSLog(@"%d*****%@", i ,[NSThread currentThread]);
        }

    }];

    [self.queue addOperationWithBlock:^{
        NSLog(@"==============================================");
        for(int i = 0 ; i < 10000; i++){
            NSLog(@"%d*****%@", i ,[NSThread currentThread]);
        }

    }];

}
  • NSOperation的依賴(lài)和監(jiān)聽(tīng)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //創(chuàng)建隊(duì)列
    NSOperationQueue * queue1 = [[NSOperationQueue alloc] init];
    NSOperationQueue * queue2 = [[NSOperationQueue alloc] init];

    //創(chuàng)建任務(wù)
    NSBlockOperation * operation1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1==%@",[NSThread currentThread]);
    }];
    NSBlockOperation * operation2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"2==%@",[NSThread currentThread]);
    }];
    NSBlockOperation * operation3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"3==%@",[NSThread currentThread]);
    }];
    NSBlockOperation * operation4 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"4==%@",[NSThread currentThread]);
    }];

    //添加依賴(lài),并需要添加到隊(duì)列之前添加依賴(lài)
    //依賴(lài)了誰(shuí),就會(huì)在誰(shuí)執(zhí)行完之后再執(zhí)行
    //可以跨隊(duì)列: 依賴(lài)對(duì)象和被依賴(lài)對(duì)象可以不再一個(gè)隊(duì)列
    [operation4 addDependency:operation1];
    [operation4 addDependency:operation2];
    [operation4 addDependency:operation3];

    //添加監(jiān)聽(tīng)
    //任務(wù)執(zhí)行完之后,就會(huì)調(diào)用這個(gè)block,在子線程中執(zhí)行
    [operation4  setCompletionBlock:^{
        NSLog(@"operation4執(zhí)行完畢. %@",[NSThread currentThread]);
    }];

    //把任務(wù)添加到隊(duì)列中
    [queue1 addOperation:operation1];
    [queue1 addOperation:operation2];

    [queue2 addOperation:operation3];
    [queue2 addOperation:operation4];
}
  • 線程間的通信

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];

    [queue addOperationWithBlock:^{
       //耗時(shí)操作

        //回到主線程刷新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //刷新UI
        }];
    }];

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蒲凶,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件带射,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)卦羡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)麦到,“玉大人绿饵,你說(shuō)我怎么就攤上這事∑康撸” “怎么了拟赊?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)粹淋。 經(jīng)常有香客問(wèn)我吸祟,道長(zhǎng),這世上最難降的妖魔是什么桃移? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任欢搜,我火速辦了婚禮,結(jié)果婚禮上谴轮,老公的妹妹穿的比我還像新娘炒瘟。我一直安慰自己,他們只是感情好第步,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布疮装。 她就那樣靜靜地躺著缘琅,像睡著了一般。 火紅的嫁衣襯著肌膚如雪廓推。 梳的紋絲不亂的頭發(fā)上刷袍,一...
    開(kāi)封第一講書(shū)人閱讀 51,258評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音樊展,去河邊找鬼呻纹。 笑死,一個(gè)胖子當(dāng)著我的面吹牛专缠,可吹牛的內(nèi)容都是我干的雷酪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼涝婉,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼哥力!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起墩弯,我...
    開(kāi)封第一講書(shū)人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤吩跋,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后渔工,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體锌钮,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年引矩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了轧粟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡脓魏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出通惫,到底是詐尸還是另有隱情茂翔,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布履腋,位于F島的核電站珊燎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏遵湖。R本人自食惡果不足惜悔政,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望延旧。 院中可真熱鬧谋国,春花似錦、人聲如沸迁沫。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至近弟,卻和暖如春缅糟,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背祷愉。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工窗宦, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人二鳄。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓赴涵,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親泥从。 傳聞我的和親對(duì)象是個(gè)殘疾皇子句占,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容