标签:
为了方便的使用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), ^{
//汇总结果
});
//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;
}标签:
原文地址:http://blog.csdn.net/haogaoming123/article/details/46646637