0

在我的项目中,程序在查询数据库时会触发一个动画,当它接收到响应数据时,它会自动触发另一个动画来显示数据。

-(void)queryDatabase{
    //...querying database ...
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{ 
                       //...first animation block...
                     }
                     completion:^(BOOL finished){
                       //...first completion block...
                     }];
}

-(void)receivedResponse:(NSData *)responseData{
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{ 
                       //...second animation block...
                     }
                     completion:^(BOOL finished){
                       //...second completion block...
                     }];
}

我的问题是,当程序启动并在第一次收到响应时触发第二个动画,“第二个动画块”完全执行,但“第二个完成块”没有执行,直到大约 20 屏幕才改变或更多秒过去了。之后,当再次调用此循环时,第二个动画将始终正常工作。怎么修?

4

1 回答 1

3

首先,所有 UI 代码都应该在主线程上执行。如果你不遵守这一点,你会得到意想不到的结果。当我想要运行一些 UI 代码时,我完全没有遇到任何事情发生,而每当我错误地在后台线程上运行 UI 代码时,应用程序就会挂起。有很多关于为什么 UI 代码必须在主线程上运行的讨论。

如果您知道收到的响应方法将在主线程以外的线程上执行,您可以使用 Grand Central Dispatch (GCD) 轻松地将其带回主线程。GCD 比 performSelectorOnMainThread 方法好用得多...

-(void)receivedResponse:(NSData *)responseData{
    dispatch_async(dispatch_get_main_queue(), ^{
        // put your UI code in here
    });
}
于 2014-01-07T11:26:52.573 回答