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; }