项目中偶尔会遇到在一个控制器需要发起多个网络请求,拿到数据后再去刷新UI界面。那么在这样的情况下GCD派上用场了。
demo中,用sleep(),模拟网络请求时差,NSLog打印,以达到演示目的。
image.png
//
// ViewController.m
// dispatch_group_Demo
//
// Created by GrabinWong on 2017/12/6.
// Copyright © 2017年 GrabinWong. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self startTask];
}
- (void)startTask
{
NSLog(@"test..");
sleep(5);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self startFirstTask];
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self startSecondTask];
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"所有任务都完成了");
});
}
- (void)startFirstTask
{
NSLog(@"假装是个网络请求任务一开始!");
sleep(6);
for (int i = 1 ; i <= 6; i++) {
NSLog(@"任务一正在进行中...%d..",i);
}
NSLog(@"任务一完成");
}
- (void)startSecondTask
{
NSLog(@"假装是个网络请求任务二开始!");
sleep(9);
for (int i = 1 ; i <= 9; i++) {
NSLog(@"任务二正在进行中...%d..",i);
}
NSLog(@"任务二完成");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论