多線程-NSInvocationOperation

在NSThread中提供了三種使用方式,其中一種可以獲取一個(gè)NSThread對(duì)象,通過(guò)調(diào)用start方法開(kāi)始執(zhí)行任務(wù),在NSOperation中也是存在start對(duì)象方法的,接下來(lái)就演示下NSInvocationOperation的使用以及start方法使用上的注意

示例代碼:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
     [self test1];
    // [self test2];
}
// 開(kāi)辟新線程
- (void)test1{
    
    // 1.創(chuàng)建操作對(duì)象
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demo) object:nil];
    // 2.創(chuàng)建隊(duì)列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    // 3.將操作對(duì)象添加到隊(duì)列中
    [queue addOperation:operation];
    
    // LOG: -[ViewController demo]--><NSThread: 0x7fecf0c01020>{number = 2, name = (null)}
}

// 沒(méi)有開(kāi)辟新線程
- (void)test2{
    
    // 1.創(chuàng)建操作對(duì)象
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demo) object:nil];
    
    // 2.開(kāi)始執(zhí)行操作
    [operation start];
    
    // LOG:  -[ViewController demo]--><NSThread: 0x7fbcf2604e80>{number = 1, name = main}

}

// 被調(diào)用的方法
- (void)demo{
    
    NSLog(@"%s-->%@",__func__,[NSThread currentThread]);
}

@end

結(jié)論:

NSInvocationOperation中默認(rèn)情況下調(diào)用start方法后并不會(huì)開(kāi)一條新線程去執(zhí)行操作,而是在當(dāng)前線程同步執(zhí)行操作
只有將NSOperation放到一個(gè)NSOperationQueue中,才會(huì)異步執(zhí)行操作

在調(diào)用start方法和將操作對(duì)象添加到隊(duì)列中時(shí),系統(tǒng)最終都會(huì)調(diào)用一個(gè) "- (void)main;"方法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容