多线程和一般层次结构理解

麦克马坦

每当我的应用程序变得更复杂时,它就会达到视图刷新的速度不如我希望的那样快。

例如,如果我有一个播放器按钮,并且每当用户单击该按钮时,该按钮将更改其图像,然后播放器将播放一些音乐,该图像需要很长时间才能更改。

无论是否在更改图像后出现“ SetNeedsdisplay”,或者即使我为更改图像使用“ preformSelectorOnMainThred”,这种情况都不会发生。

我添加并显示了我的意思的代码捕捉:

- (IBAction)playButtonPressed:(id)sender {


//This is the  image change, plus a small animation that should happen:
dispatch_async(dispatch_get_main_queue(), ^{

    [self.playButtonImage setImage:[UIImage imageNamed:@"PlayDiscButtonPressedMC"]];
    [[self superview] setNeedsDisplay];

    [self performSelector:@selector(animationInsertDisk) withObject:nil];

});

//This is the methus that will call the player to start playing, by delegate.
 [self performSelector:@selector(callDelegate) withObject:nil];;


}

发生的是,由于之后出现的“ callDelegate”,因此更改图像和动画大约需要1-2秒才能完成!假设我删除了“ callDelegate”,则图像和动画将在两岸消失!

我不明白为什么会这样,难道不是最先出现的代码会先发生吗?主线程上发生的情况还不够吗?

在这里的任何帮助将不胜感激!谢谢!!

苏尔坦

我会尽力解释

dispatch_async将区块中的所有内容安排在不久的将来。例如,如果调用dispatch_async按钮点击处理程序,则在方法结束并将控件返回给系统之前,代码将不会执行。

[self performSelector:@selector(callDelegate) withObject:nil];

和写作一样

[self callDelegate];

这是一个简单的方法调用。这是一个阻塞电话。如果调用需要一些时间,则UI中的所有内容都必须等待(因为您是从UI线程调用的)。

您的代码基本上与以下代码相同:

- (IBAction)playButtonPressed:(id)sender {

    [self callDelegate];

    dispatch_async(dispatch_get_main_queue(), ^{
       [self.playButtonImage setImage:[UIImage imageNamed:@"PlayDiscButtonPressedMC"]];

       //no need for this here. Don't try to fix bugs by adding random code.
       //[[self superview] setNeedsDisplay];

       //performSelector just calls the method, so a direct call is exactly the same
       [self animationInsertDisk];
     });
}

现在,我不确定您想通过该方法实现什么dispatch_async您希望动画立即开始并且您已经在主线程上,所以只需

- (IBAction)playButtonPressed:(id)sender {
    [self.playButtonImage setImage:[UIImage imageNamed:@"PlayDiscButtonPressedMC"]];
    [self animationInsertDisk];

    [self callDelegate];
}

但是,“滞后”可能是由于您从主线程启动播放器并阻塞主线程一段时间而造成的。我不确定您到底在做什么,[self callDelegate]但是通过打包此电话dispatch_async可能会有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章