iOS开发之GCD使用
iOS开发之GCD使用
(1)使用GCD创建一个异步任务
#pragma mark - 使用GCD创建一个异步任务 - (void)createAsyncTask { //创建一个异步任务 //参数1:传入queue,有3种queue //main queue 主队列(UI主线程) //global queue 全局队列(理解为工作线程) //自定义queue dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ for (int i=0; i<20; i++) { NSLog(@"A = %d",i); } }); dispatch_async(queue, ^{ for (int i=0; i<20; i++) { NSLog(@"B = %d",i); } }); }
(2)模拟网络下载
#pragma mark - 模拟网络下载 - (void)simulateNetwordDownload { _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(10, 100, 300, 20)]; [self.view addSubview:_progressView]; //GCD最简单开启异步任务的形式 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (int i=0; i<100; i++) { //子线程中不能直接更新UI // progressView.progress+=0.01; //(1)更新UI dispatch_get_main_queue() 作用:切回主线程更新UI dispatch_async(dispatch_get_main_queue(), ^{ _progressView.progress+=0.01; }); [NSThread sleepForTimeInterval:0.1]; } //(2)最后显示对话框 dispatch_async(dispatch_get_main_queue(), ^{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载完成" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil]; [alert show]; }); //(1)(2)同步执行,先(1)后(2) }); }
(3)只执行一次,实现单例(推荐实现的方式,线程安全)
#pragma mark - 只执行一次,实现单例(推荐实现的方式,线程安全) - (void)runOnce { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@"只执行一次的代码"); }); }
(4)延时执行
#pragma mark - 延时执行 - (void)delayRun { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSLog(@"1111111"); }); }
(5)通知同时异步执行多个任务,等待所有任务下载完成进行处理(类似迅雷)
#pragma mark - 通知执行多个任务,等待所有任务下载完成进行处理(类似迅雷) - (void)groupRun { //group 任务组 dispatch_group_t group = dispatch_group_create(); //7s完成 dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (int i=0; i<100; i++) { NSLog(@"A = %d",i); [NSThread sleepForTimeInterval:0.07]; } }); //5s完成 dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (int i=0; i<100; i++) { NSLog(@"B = %d",i); [NSThread sleepForTimeInterval:0.05]; } }); //10s完成 dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (int i=0; i<100; i++) { NSLog(@"C = %d",i); [NSThread sleepForTimeInterval:0.1]; } }); dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"所有任务完成,自动关机"); }); }