@interface ViewController : UIViewController @property (nonatomic,strong)void (^loggerBlock)(void); @end - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; // GCD極大的方便了多線程編程,應該儘可能使用GCD來處理後臺線程和UI線程的交互 // block的定義 調用 [self block]; // 修改block以外的變量 [self ModifyBlock]; // 系統提供的dispatch方法 [self dispatch]; // 自定義queue,用dispatch_queue_create [self configQueue]; // 高級用法 兩個線程後臺並行運行,等到兩個線程都結束後,在彙總執行結果 [self advancedDispatch]; //延長應用在後臺運行事件,在Appdelegate設置 } -(void)block { _loggerBlock = ^{ NSLog(@"HelloWorld"); }; //延時操做 dispatch_time_t deleyTime = dispatch_time(DISPATCH_TIME_NOW, 5.0 *NSEC_PER_SEC); dispatch_after(deleyTime, dispatch_get_main_queue(), ^{ NSLog(@"延時調用"); // 調用 _loggerBlock(); }); } -(void)ModifyBlock { __block int a = 0; void (^foo)(void) =^{ a = 1; NSLog(@"%d",a); }; foo(); } -(void)dispatch { //後臺執行: dispatch_async(dispatch_get_global_queue(0, 0), ^{ //something }); //主線程執行 dispatch_async(dispatch_get_main_queue(), ^{ //something }); // 一次性執行 通常用在單例線程安全模式 static dispatch_once_t onceTaken; dispatch_once(&onceTaken,^{ //Tools *t = [Tools alloc]init]; }); // 延遲執行 double delayInTime = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInTime * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^{ //在主線程延遲執行的事件 }); } -(void)configQueue { dispatch_queue_t urls_queue = dispatch_queue_create("http://my.oschina.net/u/2319073/admin/new-blog", NULL); dispatch_async(urls_queue, ^{ // your coder }); // dispatch_release(urls_queue); } -(void)advancedDispatch { //分段下載進度條 dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ //並行執行的線程一 }); dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ //並行執行的線程二 }); dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ //彙總結果 }); } // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (nonatomic,strong)void (^loggerBlock)(void); @end - (void)applicationDidEnterBackground:(UIApplication *)application { [self beingBackgroundUpdateTask]; // 須要長久運行的代碼 [self endBackgroundUpdateTask]; } #pragma 延長後臺運行時間 -(void)beingBackgroundUpdateTask { self.backgroundUpdateTask = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^{ [self endBackgroundUpdateTask]; }]; } -(void)endBackgroundUpdateTask { [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask]; self.backgroundUpdateTask = UIBackgroundTaskInvalid; }