iosNSOperation依賴關係

來源:互聯網
上載者:User

標籤:ios開發   多線程   線程   ios   非同步   

NSOperation 依賴關係,就像你和女友,互相需要對方一樣。非常有意思。

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

 


    //操作依賴

    //處理圖片的耗時操作在子線程中執行

    NSBlockOperation *blockOp = [NSBlockOperationblockOperationWithBlock:^{

        

        NSLog(@"blockOp下載圖片 thread = %@",[NSThreadcurrentThread]);

        

    }];

    

    NSBlockOperation *blockOp1 = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"blockOp1給圖片添加浮水印 thread = %@",[NSThreadcurrentThread]);

    }];

    

    

    NSBlockOperation *blockOp2 = [NSBlockOperationblockOperationWithBlock:^{

        [NSThreadsleepForTimeInterval:2.0];

    

        NSLog(@"blockOp2儲存圖片 thread = %@",[NSThreadcurrentThread]);

    }];

    

    

    //給blockOp1添加依賴關係,使blockOp1在blcokOp執行結束後執行

    [blockOp1 addDependency:blockOp];//也就是下載結束之後再給圖片添加浮水印,然後儲存圖片。一種依賴關係

    [blockOp2 addDependency:blockOp1];

    

    //建立隊列(把上面要乾的事情丟到隊列中同時執行--有點類似GCD中的非同步,並發,開啟了多個線程)

    NSOperationQueue *queue = [[NSOperationQueuealloc]init];

    //添加到隊列

    [queue addOperation:blockOp];

    [queue addOperation:blockOp1];

    [queue addOperation:blockOp2];

    

    //設定隊列中操作同時執行的最大數目,也就是說當前隊列中呢最多由幾個線程在同時執行,一般情況下允許最大的並發數2或者3

    [queue setMaxConcurrentOperationCount:3];

    

    //

    for (int i =0; i<50; i++) {

        NSBlockOperation *blockOpp = [NSBlockOperationblockOperationWithBlock:^{

            NSLog(@"blockOpp i = %d thread = %@",i,[NSThreadcurrentThread]);

        }];

        

        [queue addOperation:blockOpp];

        

    }

    

    //重新整理UI的操作依賴關係必須在主線程中執行

    NSBlockOperation *blocOpMain = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"blockOpMain重新整理UI 顯示圖片,thread = %@",[NSThreadcurrentThread]);

    }];

    

    //這兩個操作的依賴關係,跨隊列

    [blocOpMain addDependency:blockOp2];

    

    //主隊列

    [[NSOperationQueuemainQueue]addOperation:blocOpMain];

    

}

@end


iosNSOperation依賴關係

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.