线程互动,GCD小应用,(功能实现并代码聚集---加载动画,弹框AlertView定时消失。)

GCD线程间互动应用,简单小示例:

1.让提醒框弹出(主线程任务),然后开启一个异步线程睡眠2秒后是主线程中的弹框消失。

[anet getAccessFaildFunc:^(NSString *errorMSG) {

     _alertView = [[UIAlertView alloc] initWithTitle:errorMSG message:self.inputErrormsg delegate:self cancelButtonTitle:nil otherButtonTitles:nil];

//这个弹框,如果不想用代理,只需要delegate:nil,让后cancelBtn不为空,给一个,当弹框出来后点击该按钮,会将弹框释放。

     [_alertView show];

实现一秒钟后提醒框消失。

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

          sleep(2.0f);

          dispatch_async(dispatch_get_main_queue(), ^{

              [_alertView dismissWithClickedButtonIndex:0 animated:YES];

          });

      });

}];

2.让程序启动加载时候现实加载图片2秒,让后回到主线程加载界面

[self.window addSubview:_loadImgView];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

/*可以在这块异步线程中实现一些耗时的数据初始化任务*/

      sleep(2.0f);//在子线程中计时,不影响主线程的工作。

      dispatch_async(dispatch_get_main_queue(), ^{

          [_tbc.tabBar setHidden:YES];

          self.window.rootViewController  = _tbc;

          [UIView animateWithDuration:0.5 animations:^{

            [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.window cache:NO];

          } completion:^(BOOL finished) {

               [_loadImgView removeFromSuperview];//不需要的图片还是去掉好,耗内存。

          }];

      });

});

原文地址:https://www.cnblogs.com/longtaozi/p/3843714.html