小胖說事20--------GCD筆記

來源:互聯網
上載者:User

標籤:

1.系統提供的dispatch方法

   為了方便的使用GCD,蘋果提供了一些方法方便我們將BLOCK放在主線程或者背景程式執行,或者延後執行。

    //後台執行:    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        //something    });    //主線程執行    dispatch_async(dispatch_get_main_queue(), ^{        //something    });    //一次執行完    static dispatch_once_t once;    dispatch_once(&once, ^{        //something    });    //延遲2秒執行    double delayInSeconds = 2.0;    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);    dispatch_after(popTime, dispatch_get_main_queue(), ^{        //something    });
     dipatch_queue_t也可以自己定義,通過dispatch_queue_creat方法實現,例如:

    dispatch_queue_t my_queue = dispatch_queue_create("myQueue", NULL);    dispatch_async(my_queue, ^{        //something    });    dispatch_release(my_queue);
      另外GCD還有一些進階用法,比如,讓後台兩個線程並存執行,然後等兩個線程都結束後,在匯總執行結果:    

    dispatch_group_t group = dispatch_group_create();    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        //並存執行的線程1    });    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        //並存執行的線程2    });    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        //匯總結果    });

2.後台運行   使用block可以讓程式在後台較長久的運行,以前的時候應該被按HOME鍵之後,最多隻有5秒鐘的後台已耗用時間,但是應用可以調用UIApllication的beginBackgroundTaskWithExoirationHandler方法,讓應用程式最多有10分鐘的時間在後台運行,這個時候可以做清理緩衝,發送統計資料等等。
//AppDelegate.h檔案@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundUpdateTask;
//APPDelegate.m- (void)applicationDidEnterBackground:(UIApplication *)application {        [self beginBackgrooundUpdateTask];    //在這裡加上你需要長久啟動並執行代碼    [self  endBackgrooundUpdateTask];}-(void)beginBackgrooundUpdateTask{    self.backBackgroundUpdateTask = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^{        [self  endBackgrooundUpdateTask];    }];}-(void)endBackgrooundUpdateTask{    [[UIApplication sharedApplication] endBackgroundTask:self.backBackgroundUpdateTask];    self.backBackgroundUpdateTask = UIBackgroundTaskInvalid;}

小胖說事20--------GCD筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.