在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;"方法