iOS詳解多線程(實現篇——NSOperation)


上一節中,我們探究了GCD實現多線程的各種方式,有圖有真相,不清楚的朋友們可以回去看一看啦。這一節中,我們來看看蘋果官方給我們提供的又一個實現多線程的方式,NSOperation。

GCD鏈接:iOS詳解多線程(實現篇——GCD)
NSThread鏈接:詳解多線程(實現篇——NSThread)
多線程概念篇鏈接:詳解多線程(概念篇——進程、線程以及多線程原理)

源碼鏈接:https://github.com/weiman152/Multithreading.git

多線程的實現方法

1.NSThread(OC)

2.GCD(C語言)

3.NSOperation(OC)

4.C語言的pthread(C語言)
5.其他實現多線程方法

本節主要內容
1.NSOperation是什麼
2.NSOperation的使用
2_1.NSOperation對象的創建(三種方式)
2_2. NSOperationQueue的使用
2_3. 任務和隊列結合使用

  1. NSOperation其他重要用法
    3_1. NSOperation的依賴
    4.案例
1.NSOperation是什麼

NSOperation是蘋果官方提供的面向對象的一種解決多線程的方式。NSOperation是對GCD的封裝。我們已經知道,GCD是C語言風格的,NSOperation是OC的面向對象的,比GCD多了一些更加簡單實用的功能,使用起來更加的便捷,容易理解。
NSOperation 和NSOperationQueue 分別對應 GCD 的 任務 和 隊列。

2.NSOperation的使用

我們現在知道,NSOperation是對GCD的封裝,複習一下GCD的使用步驟:
1.創建隊列(串行、併發);
2.創建任務(同步、異步);
把任務放在隊列中執行。

NSOperation的使用也是差不多的步驟:
1.將任務封裝到NSOperation對象中;
2.將NSOperation對象添加到NSOperationQueue中;
系統會自動將NSOperationQueue中的NSOperation取出來,並將取出的NSOperation封裝的操作放到一條新線程中執行。

2.1 NSOperation對象的創建
注意:NSOperation是一個抽象類,不具備封裝操作的能力,必須使用它的子類。

NSOperation有三個子類都可以創建任務對象。
1》NSInvocationOperation

先創建一個待執行的函數,run

-(void)runWithName:(NSString *)name{
    NSLog(@"-------%@-------",name);
    NSLog(@"當前線程:%@",[NSThread currentThread]);
    NSLog(@"哈哈哈哈,我是個任務,要執行2秒哦");
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"任務結束啦");
}

NSInvocationOperation執行run方法。

- (IBAction)test1:(id)sender {
    //1.NSInvocationOperation
    NSInvocationOperation * invocationOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(runWithName:) object:@"NSInvocationOperation"];
    //啓動
    [invocationOp start];
}

結果:


2》NSBlockOperation
NSBlockOperation是最常用的一種方式了,可以追加任務,並且追加的任務是在子線程中執行的。

- (IBAction)test2:(id)sender {
    //2.NSBlockOperation(最常使用)
    NSBlockOperation * blockOp = [NSBlockOperation blockOperationWithBlock:^{
        //要執行的操作,目前是主線程
        NSLog(@"NSBlockOperation 創建,線程:%@",[NSThread currentThread]);
    }];
    //2.1 追加任務,在子線程中執行
    [blockOp addExecutionBlock:^{
        NSLog(@"追加任務一");
        [self runWithName:@"NSBlockOperation 追加"];
    }];
    [blockOp addExecutionBlock:^{
        NSLog(@"追加任務二, %@",[NSThread currentThread]);
    }];
    [blockOp start];
}

結果:


3》自定義類繼承自NSOperation,實現main方法。
我們創建一個類WMOperation繼承自NSOperation,如下圖:


實現main方法:


使用:

- (IBAction)test3:(id)sender {
    WMOperation * wmOp = [[WMOperation alloc] init];
    [wmOp start];
}

結果:


上面是最簡單的自定義Operation,是一種串行操作,也是在主線程進行的操作。爲了更好的探究自定義類,我們再新建兩個類,一個是複雜一點的串行,一個是並行操作。
新建兩個類,如下圖:


WMCXOperation:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
/**
 自定義串行操作,NSOperation的子類
 */
@interface WMCXOperation : NSOperation

@end

NS_ASSUME_NONNULL_END

#import "WMCXOperation.h"

@implementation WMCXOperation

- (void)main {
    NSLog(@"main 開始啦");
    @try {
        //任務是否結束標識
        BOOL isFinish = NO;
        //只有當沒有執行完成和沒有被取消,才執行自定義的相應操作
        while (isFinish==NO&&(self.isCancelled==NO)) {
            //睡眠1秒,模擬耗時
            sleep(1);
            NSLog(@"線程:%@",[NSThread currentThread]);
            isFinish = YES;
        }
    } @catch (NSException *exception) {
        NSLog(@"出現異常:%@",exception);
    } @finally {
        NSLog(@"哈哈哈");
    }
    NSLog(@"main 結束啦");
}

@end

測試:

- (IBAction)test3:(id)sender {
    WMOperation * wmOp = [[WMOperation alloc] init];
    [wmOp start];
    
    //自定義串行
    WMCXOperation * cxOp = [[WMCXOperation alloc] init];
    NSLog(@"任務開始");
    [cxOp start];
    NSLog(@"任務結束");
    
    //自定義並行
}

結果:


從結果可以看出,任務的執行依然是在主線程,是串行操作。

自定義並行操作:
WMBXOperation

//
//  WMBXOperation.h
//  Multithreading
//
//  Created by wenhuanhuan on 2020/10/14.
//  Copyright © 2020 weiman. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
/**
自定義並行操作,NSOperation的子類
 
 自定義並行的 NSOperation 則要複雜一點,首先必須重寫以下幾個方法:

 start: 所有並行的 Operations 都必須重寫這個方法,然後在你想要執行的線程中手動調用這個方法。注意:任何時候都不能調用父類的start方法。
 main: 在start方法中調用,但是注意要定義獨立的自動釋放池與別的線程區分開。
 isExecuting: 是否執行中,需要實現KVO通知機制。
 isFinished: 是否已完成,需要實現KVO通知機制。
 isConcurrent: 該方法現在已經由isAsynchronous方法代替,並且 NSOperationQueue 也已經忽略這個方法的值。
 isAsynchronous: 該方法默認返回 NO ,表示非併發執行。併發執行需要自定義並且返回 YES。後面會根據這個返回值來決定是否併發。
 與非併發操作不同的是,需要另外自定義一個方法來執行操作而不是直接調用start方法.
*/
@interface WMBXOperation : NSOperation

//自定義方法,啓動操作
-(BOOL)wmStart:(NSOperation *)op;

@end

NS_ASSUME_NONNULL_END

//
//  WMBXOperation.m
//  Multithreading
//
//  Created by wenhuanhuan on 2020/10/14.
//  Copyright © 2020 weiman. All rights reserved.
//

#import "WMBXOperation.h"

@interface WMBXOperation()
{
    BOOL executing;
    BOOL finished;
}
@end

@implementation WMBXOperation

//重寫init方法
-(instancetype)init{
    if (self = [super init]) {
        executing = NO;
        finished = NO;
    }
    return self;
}

//重寫start方法
-(void)start{
    //如果任務被取消了
    if (self.isCancelled) {
        [self willChangeValueForKey:@"isFinished"];
        finished = YES;
        [self didChangeValueForKey:@"isFinished"];
        return;
    }
    
    [self willChangeValueForKey:@"isExecuting"];
    //使用NSThread開闢子線程執行main方法
    [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
    executing = YES;
    [self didChangeValueForKey:@"isExecuting"];
}

//重寫main方法
-(void)main {
    NSLog(@"main 開始");
    @try {
        // 必須爲自定義的 operation 提供 autorelease pool,因爲 operation 完成後需要銷燬。
        @autoreleasepool {
            BOOL isfinish = NO;
            while (isfinish==NO&&self.isCancelled==NO) {
                NSLog(@"線程: %@", [NSThread currentThread]);
                isfinish = YES;
            }
            [self completeOperation];
        }
    } @catch (NSException *exception) {
        NSLog(@"異常:%@",exception);
    } @finally {
        NSLog(@"嘿嘿");
    }
    
    NSLog(@"main 結束");
}

- (void)completeOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
    
    executing = NO;
    finished = YES;
    
    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}

-(BOOL)isAsynchronous{
    return YES;
}

-(BOOL)isExecuting{
    return executing;
}

-(BOOL)isFinished{
    return finished;
}

-(BOOL)wmStart:(NSOperation *)op{
    BOOL run = NO;
    if ([op isReady]&&![op isCancelled]) {
        if ([op isAsynchronous]==NO) {
            [op start];
        }else{
            [NSThread detachNewThreadSelector:@selector(start) toTarget:op withObject:nil];
        }
        run = YES;
    }else if ([op isCancelled]){
        [self willChangeValueForKey:@"isFinished"];
        [self willChangeValueForKey:@"isExecuting"];
        executing = NO;
        finished = YES;
        [self didChangeValueForKey:@"isExecuting"];
        [self didChangeValueForKey:@"isFinished"];
        run = YES;
    }
    
    return run;
}

@end

測試:

- (IBAction)test3:(id)sender {
    WMOperation * wmOp = [[WMOperation alloc] init];
    [wmOp start];
    
    //自定義串行
    WMCXOperation * cxOp = [[WMCXOperation alloc] init];
    NSLog(@"任務開始");
    [cxOp start];
    NSLog(@"任務結束");
    
    //自定義並行
    WMBXOperation * bxOp = [[WMBXOperation alloc] init];
    NSLog(@"並行任務開始");
    [bxOp wmStart:bxOp];
    NSLog(@"並行任務結束");
}

打印結果:


從結果可以看出,是在新的子線程中執行的任務。
當然了,因爲我們再自定義類的代碼中使用了NSthread的開啓子線程的方法:


2.2 NSOperationQueue的使用

NSOperationQueue相當於GCD的隊列。NSOperation有兩種隊列:

1.主隊列:mainQueue,在主隊列中的任務都在主線程執行。
2.其他隊列:非主隊列通過設置最大併發數確定是串行還是併發隊列。

//主隊列
- (IBAction)mainQ:(id)sender {
    NSOperationQueue * q1 = [NSOperationQueue mainQueue];
}

//非主隊列
- (IBAction)otherQ:(id)sender {
    NSOperationQueue * q2 = [[NSOperationQueue alloc] init];
}

NSOperationQueue的作用

NSOperation的子類對象是通過調用start方法來啓動任務的。如果將對象添加到NSOperationQueue中,就不需要手動啓動了。

添加任務到隊列的兩個方法:
-(void)addOperation:(NSOperation *)op;
-(void)addOperationWithBlock:(void (^)(void))block;

下面,我們就把任務和隊列結合起來,實現多線程。

2.3 NSOperation子類和NSOperationQueue結合使用創建多線程

NSBlockOperation 不論封裝操作還是追加操作都是異步併發執行

1》NSBlockOperation+主隊列

//block+主隊列
- (IBAction)blockAndMain:(id)sender {
    //1.創建主隊列
    NSOperationQueue * q1 = [NSOperationQueue mainQueue];
    //2.創建任務
    NSBlockOperation * p1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務一,當前線程:%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務一結束");
    }];
    [p1 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:1.0];
        NSLog(@"任務二,線程:%@",[NSThread currentThread]);
    }];
    [p1 addExecutionBlock:^{
        NSLog(@"任務三,線程:%@",[NSThread currentThread]);
    }];
    //3.把任務添加到隊列
    [q1 addOperation:p1];
    
    //也可以直接添加操作到隊列中
    [q1 addOperationWithBlock:^{
        NSLog(@"直接添加操作,%@",[NSThread currentThread]);
    }];
}

結果:



從結果可以看出,三個操作是併發執行的,雖然是在主隊列中添加任務,但是任務並不是都在主線程執行,而是有在主線程也有在子線程中併發執行的。

2》NSBlockOperation+非主隊列

//block+非主隊列
- (IBAction)blockAndOther:(id)sender {
    //創建非主隊列
    NSOperationQueue * q1 = [[NSOperationQueue alloc] init];
    NSBlockOperation * b1 = [[NSBlockOperation alloc] init];
    [b1 addExecutionBlock:^{
        NSLog(@"任務一,線程:%@",[NSThread currentThread]);
    }];
    [b1 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務二,線程:%@",[NSThread currentThread]);
    }];
    [b1 addExecutionBlock:^{
        NSLog(@"任務三,線程:%@",[NSThread currentThread]);
    }];
    //把任務添加到隊列
    [q1 addOperation:b1];
}

結果:

其實,我們只使用NSBlockOperation也是可以實現多線程的,只是需要我們自己手動開啓任務。

//block+非主隊列
- (IBAction)blockAndOther:(id)sender {
    //創建非主隊列
    NSOperationQueue * q1 = [[NSOperationQueue alloc] init];
    NSBlockOperation * b1 = [[NSBlockOperation alloc] init];
    [b1 addExecutionBlock:^{
        NSLog(@"任務一,線程:%@",[NSThread currentThread]);
    }];
    [b1 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務二,線程:%@",[NSThread currentThread]);
    }];
    [b1 addExecutionBlock:^{
        NSLog(@"任務三,線程:%@",[NSThread currentThread]);
    }];
    //把任務添加到隊列
    [q1 addOperation:b1];
    
    //只使用NSBlockOperation
    NSLog(@"-------只使用NSBlockOperation實現------------");
    NSBlockOperation * b2 = [[NSBlockOperation alloc] init];
    [b2 addExecutionBlock:^{
        NSLog(@"1,線程:%@",[NSThread currentThread]);
    }];
    [b2 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"2,線程:%@",[NSThread currentThread]);
    }];
    [b2 addExecutionBlock:^{
        NSLog(@"3,線程:%@",[NSThread currentThread]);
    }];
    [b2 start];
}

結果:


3》NSInvocationOperation+主隊列

- (IBAction)InvoAndMain:(id)sender {
    NSOperationQueue * mainQ = [NSOperationQueue mainQueue];
    NSInvocationOperation * p1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task1) object:nil];
    NSInvocationOperation * p2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task2) object:nil];
    NSInvocationOperation * p3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task3) object:nil];
    [mainQ addOperation:p1];
    [mainQ addOperation:p2];
    [mainQ addOperation:p3];
}

-(void)task1 {
    NSLog(@"任務一, %@",[NSThread currentThread]);
}

-(void)task2 {
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"任務二, %@",[NSThread currentThread]);
}

-(void)task3 {
    NSLog(@"任務三, %@",[NSThread currentThread]);
}

結果:


任務在主隊列順序執行,也就是串行。

4》NSInvocationOperation+非主隊列

- (IBAction)invoAndOther:(id)sender {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    NSInvocationOperation * p1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task1) object:nil];
    NSInvocationOperation * p2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task2) object:nil];
    NSInvocationOperation * p3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task3) object:nil];
    [queue addOperation:p1];
    [queue addOperation:p2];
    [queue addOperation:p3];
}

-(void)task1 {
    NSLog(@"任務一, %@",[NSThread currentThread]);
}

-(void)task2 {
    [NSThread sleepForTimeInterval:2.0];
    NSLog(@"任務二, %@",[NSThread currentThread]);
}

-(void)task3 {
    NSLog(@"任務三, %@",[NSThread currentThread]);
}

結果:


由結果可以看出,三個任務併發執行。

3. NSOperation其他重要用法
3.1 NSOperation的依賴 - (void)addDependency:(NSOperation *)op;

有時候,我們需要給任務添加依賴關係,比如有兩個任務op1和op2,任務2必須要等待任務1執行完成之後才能執行,這個時候就可以添加任務2依賴於任務1 .

//任務依賴
- (IBAction)test1:(id)sender {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    NSBlockOperation * op1 = [[NSBlockOperation alloc] init];
    [op1 addExecutionBlock:^{
        NSLog(@"任務一, %@",[NSThread currentThread]);
    }];
    [op1 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務二,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op2 = [[NSBlockOperation alloc] init];
    [op2 addExecutionBlock:^{
        NSLog(@"op2哦,%@",[NSThread currentThread]);
    }];
    //設置op2依賴於任務op1
    //[op2 addDependency:op1];
    [queue addOperation:op1];
    [queue addOperation:op2];
}

我們在這裏有連個任務,op1和op2,兩個任務都在非主隊列中執行,我們先不添加依賴,看看執行結果:



從結果可以看出,任務一有兩個操作,任務二有一個操作,它們分別在不同的線程中執行,不分先後。
添加依賴看看:



打印結果:

從結果可以看出,添加了依賴之後,任務二隻會在任務一執行完成之後纔會執行。

3.2 NSOperation執行完成 completionBlock

如果想要在某個操作執行完成之後在執行某種操作,這個時候就可以使用completionBlock了。

//NSOperation執行完成
- (IBAction)test2:(id)sender {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務一,%@",[NSThread currentThread]);
    }];
    [op1 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務二,%@",[NSThread currentThread]);
    }];
    [op1 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:1.0];
        NSLog(@"任務三,%@",[NSThread currentThread]);
    }];
    [op1 addExecutionBlock:^{
        NSLog(@"任務四,%@",[NSThread currentThread]);
    }];
    op1.completionBlock = ^{
        NSLog(@"任務都執行完成啦");
    };
    [queue addOperation:op1];
}

打印結果:


從結果可以看出,四個任務在四個子線程中完成,直到所有的任務都執行完,才執行了completionBlock內的代碼。

3.3 最大併發數 maxConcurrentOperationCount

我們可以設置隊列的最大併發數屬性,控制隊列是併發、串行還是不執行。
maxConcurrentOperationCount>1: 併發
maxConcurrentOperationCount=1:串行
maxConcurrentOperationCount=-1:不限制,默認值
maxConcurrentOperationCount=0:不會執行任何操作
我們一起來試試。

  • 串行
//maxConcurrentOperationCount 最大併發數
- (IBAction)test3:(id)sender {
    //串行
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 1;
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務一,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務二,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務三,%@",[NSThread currentThread]);
    }];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
}

打印結果:


只開闢了一個線程,任務一個個的執行。我們把任務二改成耗時操作,看看會不會阻塞當前線程。



看看打印結果:



依然是順序執行,說明會阻塞當前線程。

注意:如果我們是一個操作中的三個子任務,我們設置隊列的最大併發數是沒有效果的,例如:

//2. 一個操作的多個任務,設置最大併發數爲1是沒有效果的
    NSOperationQueue * queue2 = [[NSOperationQueue alloc] init];
    queue2.maxConcurrentOperationCount = 1;
    NSBlockOperation * op4 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1,%@",[NSThread currentThread]);
    }];
    [op4 addExecutionBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"2,%@",[NSThread currentThread]);
    }];
    [op4 addExecutionBlock:^{
        NSLog(@"3,%@",[NSThread currentThread]);
    }];
    [queue2 addOperation:op4];

結果:



我們發現,即使我們設置了隊列的最大併發數爲1,由於我們只有一個操作,這個操作中有三個任務,這三個任務還是在三個線程中執行的,也不是順序的。由此可見,最大操作數針對的是操作,也就是NSBlockOperation對象,而不是任務。

  • 並行
    我們設置最大併發數大於1,看看結果。
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 5;
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務一,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務二,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務三,%@",[NSThread currentThread]);
    }];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];

打印結果:


我們發現三個任務是併發執行的,符合我們的預期。

  • 不執行操作,設置爲0
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 0;
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務一,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"任務二,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務三,%@",[NSThread currentThread]);
    }];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];

當我們設置了
queue.maxConcurrentOperationCount = 0;
的時候,發現不會有任何打印,操作都不再執行。

3.4 隊列暫停 suspended

當我們設置了suspended=YES之後,隊列就會暫停。

//隊列暫停,suspended
- (IBAction)test4:(id)sender {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    queue.suspended = YES
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"任務一,%@",[NSThread currentThread]);
    }];
    [op1 addExecutionBlock:^{
        NSLog(@"任務二開始,%@",[NSThread currentThread]);
        for (int i=0; i<10; i++) {
            [NSThread sleepForTimeInterval:1.0];
            NSLog(@"2: i=%d",i);
        }
        NSLog(@"任務二結束");
    }];
    [queue addOperation:op1];
}

這個時候,當我們點擊按鈕,是不會有任何操作執行的,因爲隊列暫停了。

3.5 取消隊列的未執行的所有操作
@interface OperationOtherController ()

@property(nonatomic, strong)NSOperationQueue * myQueue;

@end
//取消所有任務
- (IBAction)test5:(id)sender {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"操作一:1,%@",[NSThread currentThread]);
    }];
    [op1 addExecutionBlock:^{
        NSLog(@"操作一:2,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"操作二:1,%@",[NSThread currentThread]);
    }];
    NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"操作三:1,%@",[NSThread currentThread]);
    }];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
    self.myQueue = queue;
}
- (IBAction)cancelTest5:(id)sender {
    [self.myQueue cancelAllOperations];
}

打印結果:


我們發現,即使我們點擊了取消按鈕,未執行的操作三並沒有被取消。

注意:暫停和取消只能暫停或取消處於等待狀態的任務,不能暫停或取消正在執行中的任務,必須等正在執行的任務執行完畢之後纔會暫停,如果想要暫停或者取消正在執行的任務,可以在每個任務之間即每當執行完一段耗時操作之後,判斷是否任務是否被取消或者暫停。如果想要精確的控制,則需要將判斷代碼放在任務之中,但是不建議這麼做,頻繁的判斷會消耗太多時間

3.6 打印隊列中所有的操作對象
- (IBAction)test6:(id)sender {
    NSLog(@"打印所有操作");
    
    NSLog(@"%@",self.myQueue.operations);
}

結果:


  1. 案例:下載圖片併合成
//
//  OperationCaseController.m
//  Multithreading
//
//  Created by wenhuanhuan on 2020/10/16.
//  Copyright © 2020 weiman. All rights reserved.
//

#import "OperationCaseController.h"

@interface OperationCaseController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageV1;
@property (weak, nonatomic) IBOutlet UIImageView *imageV2;
@property (weak, nonatomic) IBOutlet UIImageView *imageVFinal;
@property(nonatomic,strong)UIImage * image1;
@property(nonatomic,strong)UIImage * image2;
@end

@implementation OperationCaseController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (IBAction)startAction:(id)sender {
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    //下載圖片一
    NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSString * str = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1601638749466&di=92ace2ffa924fe6063e7a221729006b1&imgtype=0&src=http%3A%2F%2Fpic.autov.com.cn%2Fimages%2Fcms%2F20119%2F6%2F1315280805177.jpg";
        UIImage * image = [self downLoadImage:str];
        self.image1 = image;
        //回到主線程,顯示圖片
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageV1.image = image;
        }];
    }];
    //下載圖片二
    NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSString * str = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1601638873771&di=07129fd95c56096a4282d3b072594491&imgtype=0&src=http%3A%2F%2Fimg.51miz.com%2Fpreview%2Felement%2F00%2F01%2F12%2F49%2FE-1124994-5FFE5AC7.jpg";
        UIImage * image = [self downLoadImage:str];
        self.image2 = image;
        //回到主線程,顯示圖片
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageV2.image = image;
        }];
    }];
    //合成圖片
    NSBlockOperation * op3 = [NSBlockOperation blockOperationWithBlock:^{
        UIImage * image = [self makeImage:self.image1 image2:self.image2];
        //回到主線程,顯示圖片
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageVFinal.image = image;
        }];
    }];
    //由於合成圖片要在圖片一和圖片二完成之後才能進行,所以需要添加依賴
    [op3 addDependency:op1];
    [op3 addDependency:op2];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
}

-(UIImage *)downLoadImage:(NSString *)str {
    NSLog(@"當前線程:%@",[NSThread currentThread]);
    NSURL * url = [NSURL URLWithString:str];
    NSData * data = [NSData dataWithContentsOfURL:url];
    UIImage * image = [UIImage imageWithData:data];
    return image;
}

-(UIImage *)makeImage:(UIImage *)image1 image2:(UIImage *)image2 {
    //圖形上下文開啓
    UIGraphicsBeginImageContext(CGSizeMake(300, 200));
    
    //圖形二
    [image2 drawInRect:CGRectMake(0, 0, 300, 200)];
    //圖形一
    [image1 drawInRect:CGRectMake(100, 50, 100, 100)];
    //獲取新的圖片
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    //關閉上下文
    UIGraphicsEndImageContext();
    return image;
}

@end

運行結果:


以上就是關於NSOperation創建多線程的探究內容了,如有錯漏還請指教。
祝大家生活愉快。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章