NSThread適合簡單的耗時任務的執行,它有兩種執行方法
- (void)oneClick{ [NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:@"oneClick"];}-(void)doSomething:(NSString*) str{ NSLog(@"%@",str);}- (void)twoClick{ NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"twoClick"]; [myThread start];}
NSOperation適合需要復雜的線程調度的方法,然后它默認是使用主線程不會創建子線程
- (void)threeClick{ // 1.創建NSInvocationOperation對象 NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil]; // 2.調用start方法開始執行操作 [op start];}- (void)run{ NSLog(@"------%@", [NSThread currentThread]);}- (void)fourClick{ NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{ // 在主線程 NSLog(@"1------%@", [NSThread currentThread]); }]; // 添加額外的任務(在子線程執行) [op addExecutionBlock:^{ NSLog(@"2------%@", [NSThread currentThread]); }]; [op addExecutionBlock:^{ NSLog(@"3------%@", [NSThread currentThread]); }]; [op addExecutionBlock:^{ NSLog(@"4------%@", [NSThread currentThread]); }]; [op start];}
以上這篇iOS NSThread和NSOperation的基本使用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答