常用操作
// 1.后台执行:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// something
});
//2. 主线程执行:
dispatch_async(dispatch_get_main_queue(), ^{
// something
});
//3. 一次性执行:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// code to be executed once
});
//4. 延迟2秒执行:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// code to be executed after a specified delay
});
其他高级用法
//5.单个页面多个网络请求的情况,需要监听所有网络请求结束后刷新UI
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t serialQueue = dispatch_queue_create("com.wzb.test.www", DISPATCH_QUEUE_SERIAL);
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 网络请求一
[WebClick getDataSuccess:^(ResponseModel *model) {
dispatch_group_leave(group);
} failure:^(NSString *err) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 网络请求二
[WebClick getDataSuccess:getBigTypeRM onSuccess:^(ResponseModel *model) {
dispatch_group_leave(group);
} failure:^(NSString *errorString) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
// 网络请求三
[WebClick getDataSuccess:^{
dispatch_group_leave(group);
} failure:^(NSString *errorString) {
dispatch_group_leave(group);
}];
});
// 所有网络请求结束后会来到这个方法
dispatch_group_notify(group, serialQueue, ^{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// 刷新UI
});
});
});
//6、dispatch_barrier_async的使用,dispatch_barrier_async是在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行
dispatch_queue_t queue = dispatch_queue_create("create_asy_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"dispatch_async1");
});
dispatch_async(queue, ^{
NSLog(@"dispatch_async2");
});
dispatch_barrier_async(queue, ^{
NSLog(@"dispatch_barrier_async");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"刷新界面");
});
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"dispatch_async3");
});
//7、GCD的另一个用处是可以让程序在后台较长久的运行。
在没有使用GCD时,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是在使用GCD后,app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。
让程序在后台长久运行的示例代码如下:
// AppDelegate.h文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
// AppDelegate.m文件
-(void)applicationDidEnterBackground:(UIApplication *)application {
[self beingBackgroundUpdateTask];
// 在这里加上你需要长久运行的代码
[self endBackgroundUpdateTask];
}
-(void)beingBackgroundUpdateTask {
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
-(void)endBackgroundUpdateTask {
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}