iOS 重學之路--多線程(二)

這篇文章主要是對NSOperation的,其他多線程方式請點擊這里

完整demo,請看這里

NSOperation

  • 1.1 NSOperation基本使用

(1)相關概念

01 NSOperation是對GCD的包裝
02 兩個核心概念【隊列+操作】

(2)基本使用

01 NSOperation本身是抽象類,只能只有它的子類
02 三個子類分別是:NSBlockOperation、NSInvocationOperation以及自定義繼承自NSOperation的類
03 NSOperation和NSOperationQueue結合使用實現多線程并發

(3)相關代碼

//  01 NSInvocationOperation
    //1.封裝操作
    /*
     第一個參數:目標對象
     第二個參數:該操作要調用的方法,最多接受一個參數
     第三個參數:調用方法傳遞的參數,如果方法不接受參數,那么該值傳nil
     */
//在主線程中執行
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self selector:@selector(run) object:nil];

    //2.啟動操作
    [operation start];
-------------------------------------------------
    //  02 NSBlockOperation
    //1.封裝操作
    /*
     NSBlockOperation提供了一個類方法,在該類方法中封裝操作
     */
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        //在主線程中執行
        NSLog(@"---download1--%@",[NSThread currentThread]);
    }];

    //2.追加操作,追加的操作在子線程中執行
    [operation addExecutionBlock:^{
        NSLog(@"---download2--%@",[NSThread currentThread]);
    }];

    [operation addExecutionBlock:^{
         NSLog(@"---download3--%@",[NSThread currentThread]);
    }];

    //3.啟動執行操作
    [operation start];
----------------------------------------------
// 03 自定義NSOperation
    //如何封裝操作?
    //自定義的NSOperation,通過重寫內部的main方法實現封裝操作
    //這種方式基本用不上,就一筆帶過
    -(void)main
    {
        NSLog(@"--main--%@",[NSThread currentThread]);
    }

  • 1.2 NSOperationQueue基本使用

(1)NSOperation中的兩種隊列

01 主隊列 通過mainQueue獲得,凡是放到主隊列中的任務都將在主線程執行
02 非主隊列 直接alloc init出來的隊列。非主隊列同時具備了并發和串行的功能,通過設置最大并發數屬性來控制任務是并發執行還是串行執行

(2)相關代碼

-(void)customOperation{
   //1.創建隊列
    /*
     并發:全局并發隊列,自己創建(concurrent)
     串行:主隊列,自己創建(serial)
     */
    
    //    NSOperationQueue
    /*
     主隊列:凡是放到主隊列里面的任務都在主線程執行[NSOperationQueue mainQueue]
     非主隊列:alloc int,同時具備了并發和串行的功能,默認是并發隊列
     */
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    //2.封裝操作
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download1) object:nil];
    
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download2) object:nil];
    
    NSInvocationOperation *op3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download3) object:nil];
    
    //3.添加操作到隊列
    [queue addOperation:op1];   //[op1 start]
    [queue addOperation:op2];
    [queue addOperation:op3];
}

//NSBlockOperation
- (void)block
{
    //1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    //2.封裝操作
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1----%@",[NSThread currentThread]);
    }];

    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"2----%@",[NSThread currentThread]);

    }];

    [op2 addExecutionBlock:^{
        NSLog(@"3----%@",[NSThread currentThread]);
    }];

    [op2 addExecutionBlock:^{
        NSLog(@"4----%@",[NSThread currentThread]);
    }];

    //3.添加操作到隊列中
    [queue addOperation:op1];
    [queue addOperation:op2];

    //補充:簡便方法
    [queue addOperationWithBlock:^{
        NSLog(@"5----%@",[NSThread currentThread]);
    }];

}
  • 2.3 NSOperation其它用法

(1)設置最大并發數【控制任務并發和串行】

//1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    //2.設置最大并發數
    //注意點:該屬性需要在任務添加到隊列中之前進行設置
    //該屬性控制隊列是串行執行還是并發執行
    //如果最大并發數等于1,那么該隊列是串行的,如果大于1那么是并行的
    //系統的最大并發數有個默認的值,為-1,如果該屬性設置為0,那么不會執行任何任務
    queue.maxConcurrentOperationCount = 2;

(2)暫停和恢復以及取消

    //設置暫停和恢復
    //suspended設置為YES表示暫停,suspended設置為NO表示恢復
    //暫停表示不繼續執行隊列中的下一個任務,暫停操作是可以恢復的
    if (self.queue.isSuspended) {
        self.queue.suspended = NO;
    }else
    {
        self.queue.suspended = YES;
    }

    //取消隊列里面的所有操作
    //取消之后,當前正在執行的操作的下一個操作將不再執行,而且永遠都不在執行,就像后面的所有任務都從隊列里面移除了一樣
    //取消操作是不可以恢復的
    [self.queue cancelAllOperations];

---------自定義NSOperation取消操作--------------------------
-(void)main
{
    //耗時操作1
    for (int i = 0; i<1000; i++) {
        NSLog(@"任務1-%d--%@",i,[NSThread currentThread]);
    }
    NSLog(@"+++++++++++++++++++++++++++++++++");

    //蘋果官方建議,每當執行完一次耗時操作之后,就查看一下當前隊列是否為取消狀態,如果是,那么就直接退出
    //好處是可以提高程序的性能
    if (self.isCancelled) {
        return;
    }

    //耗時操作2
    for (int i = 0; i<1000; i++) {
        NSLog(@"任務1-%d--%@",i,[NSThread currentThread]);
    }

    NSLog(@"+++++++++++++++++++++++++++++++++");
}
  • 2.4 NSOperation實現線程間通信

(1)開子線程下載圖片

 //1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    //2.使用簡便方法封裝操作并添加到隊列中
    [queue addOperationWithBlock:^{

        //3.在該block中下載圖片
        NSURL *url = [NSURL URLWithString:@"http://news.51sheyuan.com/uploads/allimg/111001/133442IB-2.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        NSLog(@"下載圖片操作--%@",[NSThread currentThread]);

        //4.回到主線程刷新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageView.image = image;
            NSLog(@"刷新UI操作---%@",[NSThread currentThread]);
        }];
    }];

(2)下載多張圖片合成綜合案例(設置操作依賴)

//02 綜合案例
- (void)download2
{
    NSLog(@"----");
    //1.創建隊列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    //2.封裝操作下載圖片1
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{

        NSURL *url = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/zhidao/pic/item/6a63f6246b600c3320b14bb3184c510fd8f9a185.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];

        //拿到圖片數據
        self.image1 = [UIImage imageWithData:data];
    }];


    //3.封裝操作下載圖片2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSURL *url = [NSURL URLWithString:@"http://pic.58pic.com/58pic/13/87/82/27Q58PICYje_1024.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];

        //拿到圖片數據
        self.image2 = [UIImage imageWithData:data];
    }];

    //4.合成圖片
    NSBlockOperation *combine = [NSBlockOperation blockOperationWithBlock:^{

        //4.1 開啟圖形上下文
        UIGraphicsBeginImageContext(CGSizeMake(200, 200));

        //4.2 畫image1
        [self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];

        //4.3 畫image2
        [self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];

        //4.4 根據圖形上下文拿到圖片數據
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//        NSLog(@"%@",image);

        //4.5 關閉圖形上下文
        UIGraphicsEndImageContext();

        //7.回到主線程刷新UI
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            self.imageView.image = image;
            NSLog(@"刷新UI---%@",[NSThread currentThread]);
        }];

    }];

    //5.設置操作依賴
    [combine addDependency:op1];
    [combine addDependency:op2];

    //6.添加操作到隊列中執行
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:combine];
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容