直接上代码、
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// [self delay];
// [self once];
// [self apply];
[self group];
}
//延时操作的几种方式
-(void)delay {
//使用NSObject 两秒后执行runing方法
[self performSelector:@selector(runing) withObject:nil afterDelay:2];
//GCD方式
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self runing];
});
//使用NSTimer repeats:参数代表是否循环
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(runing) userInfo:nil repeats:NO];
NSLog(@"########");
}
//执行的方法
-(void)runing {
NSLog(@"runing!");;
}
//一次性操作 该代码只执行一次
-(void)once {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"一次性操作");
});
}
//多次操作
-(void)apply {
//执行10次操作
dispatch_apply(10, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
//index 需要自己填写 每次遍历下标
NSLog(@"---%ld----", index);
/*
从打印结果可以看出,与for循环不一样的是,该代码使用
并行方式运行的,所以打印的下标不是按顺序。
*/
});
}
//组操作
-(void)group {
//创建组
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 方便演示,添加个循环
for (int i = 0; i < 10; i++) {
NSLog(@"任务1");
}
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i < 10; i++) {
NSLog(@"任务2");
}
});
//当1.2完成后,再去执行3
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"任务3");
});
}
@end