美文网首页
主线程阻塞问题

主线程阻塞问题

作者: 愤怒小鸟飞呀飞 | 来源:发表于2018-10-23 10:53 被阅读0次

    问题

    主线程阻塞会导致新添加在父视图的view不能及时显示。

    如下代码:

    -(void)saveButtonAction:(UIButton *)button
    {
    [SVProgressHUD showWithStatus:@"保存中。。。" maskType:SVProgressHUDMaskTypeClear];
    int m = 0 ;
    while (m < 100)
    {
    m++ ;
    NSLog(@"test");
    }
    }
    上述代码中,SVProgressHUD 将不会显示,直到 saveButtonAction 方法执行结束

    解决办法
    使用GCD异步执行,把需要执行的耗时操作,通过串行队列的方式添加到主线程队列,让主线程有时间的时候在执行
    如下代码:

    -(void)saveButtonAction:(UIButton *)button
    {
    [SVProgressHUD showWithStatus:@"保存中。。。" maskType:SVProgressHUDMaskTypeClear];
    dispatch_async(dispatch_get_main_queue(), ^{
    UIImage *image = [self getCapture];
    [self saveImageToPhotos:image];
    });
    }

    • (void)saveImageToPhotos:(UIImage*)savedImage
      {
      UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
      }

    // 指定回调方法

    • (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
      {
      NSString *msg = nil ;
      if(error != NULL){
      msg = @"保存图片失败" ;
      [SVProgressHUD showErrorWithStatus:msg];
      }else{
      msg = @"保存图片成功" ;
      [SVProgressHUD showSuccessWithStatus:msg];
      if ([self.delegate respondsToSelector:@selector(saveButtonActionComplete:)])
      {
      [self.delegate saveButtonActionComplete:self];
      }
      }
      }

    • (UIImage)getCapture
      {
      UIImage
      viewImage = nil;
      UICollectionView *scrollView = _collectionView;
      UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, scrollView.opaque, 0.0);
      {
      CGPoint savedContentOffset = scrollView.contentOffset;
      CGRect savedFrame = scrollView.frame;

        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        viewImage = UIGraphicsGetImageFromCurrentImageContext();
        
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
      

      }
      UIGraphicsEndImageContext();
      return viewImage;
      }

    相关文章

      网友评论

          本文标题:主线程阻塞问题

          本文链接:https://www.haomeiwen.com/subject/juvozftx.html