使用GCD进行线程的更好方法



好。因此,在过渡到下一个视图控制器之前,我正在尝试使用GCD处理所有重载。我正在打开大型存档文件并提取需要一些时间的提取。

整个过程都是这样:

单击uicollectionViewCell>显示活动指示器>让GCD负责重载>使用PermortSelector致电过渡选择器:OnThread:.....

问题是当我使用主要线程时,过渡发生得太快了,所有重负荷直到一段时间后才能生效,并且过渡看起来很糟糕,而在使用CurrestThread时,则需要太多时间,似乎很糟糕。

-(void)someMethod
{    
    //activity Indicator before transition begins
    UIActivityIndicatorView *activity=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [activity setFrame:self.view.bounds];
    [self.view addSubview:activity];
    [self.view bringSubviewToFront:activity];
    activity.hidesWhenStopped=YES;
    [activity startAnimating];
    dispatch_queue_t transitionQueue;
    transitionQueue = dispatch_queue_create("com.app.transitionQueue", NULL);
    dispatch_async(transitionQueue,^{
             //heavy lifting code
        viewerPVC=.....
      dispatch_async(dispatch_get_main_queue(),^{
        [activity stopAnimating];
        [self transitionToMangaViewer:mReaderPVC];
      });
    };
}
-(void)transitionToViewer:(ViewerPVC*)viewerPVC
{
    [self.navigationController pushViewController:mReaderPVC animated:YES];
}

因此尝试了第一个建议,但是过渡似乎仍然是故障的,因为Collection ViewController在过渡后仍在背景上

使用GCD时不需要使用NSTHREAD,请尝试这样的东西

dispatch_async(transitionQueue,^{
     //heavy lifting code
viewerPVC=..... //this should block here otherwise will not work
  dispatch_async(dispatch_get_main_queue(), ^{
      [activity stopAnimating];
      [self transitionToAnotherViewer:viewerPVC];
  });
});

UI更新应在主线程上进行,无需创建用于执行UI过渡的新线程。尝试以下代码:

dispatch_async(transitionQueue,^{
        //heavy lifting code
        viewerPVC=.....
        dispatch_async(dispatch_get_main_queue(), ^{
            [activity stopAnimating];
            [self performSelector:@selector(transitionToAnotherViewer:) withObject:viewerPVC waitUntilDone:YES];
        });
    };

最新更新