开发者

UI update in selector

I perform this sele开发者_高级运维ctor in my application:

- (void) doFilter:(UIButton*)button {
    [activityIndicator startAnimating];
    [self disableButtons];
    // ...
    // some actions
        // ...
    sleep(2);
    [self enableButtons];
    [activityIndicator stopAnimating];




}

when user clicks on button. activityIndicator is UIAtivityIndicatorView. But I don't see any activity indicators while this code is performing. How can I fix it?


Firstly, you should never ever use sleep on the main thread. It blocks your entire app and the user can't do anything for that time.

Secondly, the UI is not updated until your code returns control to the run loop. So whenever you call startAnimating and stopAnimating in the same method without returning to the run loop in between, you can be sure that nothing will happen in the UI (same with disableButtons and enableButtons).

Solution: call startAnimating and disableButtons. Then start the tasks you have to perform in the background so that the UI is not blocked. You can use NSOperation, performSelectorInBackground:..., Grand Central Dispatch etc. for that. Finally, when the long task is finished, have it call another method on the main thread which then calls stopAnimating and enableButtons.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜