在NSThread中提供了三種使用方式,其中一種可以獲取一個NSThread對象,通過調用start方法開始執行任務,在NSOperation中也是存在start對象方法的,接下來就演示下NSInvocationOperation的使用以及start方法使用上的注意
示例代碼:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self test1];
// [self test2];
}
// 開辟新線程
- (void)test1{
// 1.創建操作對象
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demo) object:nil];
// 2.創建隊列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 3.將操作對象添加到隊列中
[queue addOperation:operation];
// LOG: -[ViewController demo]--><NSThread: 0x7fecf0c01020>{number = 2, name = (null)}
}
// 沒有開辟新線程
- (void)test2{
// 1.創建操作對象
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demo) object:nil];
// 2.開始執行操作
[operation start];
// LOG: -[ViewController demo]--><NSThread: 0x7fbcf2604e80>{number = 1, name = main}
}
// 被調用的方法
- (void)demo{
NSLog(@"%s-->%@",__func__,[NSThread currentThread]);
}
@end
結論:
NSInvocationOperation中默認情況下調用start方法后并不會開一條新線程去執行操作,而是在當前線程同步執行操作
只有將NSOperation放到一個NSOperationQueue中,才會異步執行操作
在調用start方法和將操作對象添加到隊列中時,系統最終都會調用一個 "- (void)main;"方法