如何在线程中间更新UI ?

时间:2022-11-10 20:56:28

Below is a block of code that runs in a separate thread from my app's main thread. How do I get the UI to update after each button gets its thumbnail? Right now it doesn't update until the whole method finishes. The buttons are already added to a UIScrollView.

下面是一个代码块,它运行在我的应用程序主线程的另一个线程中。如何让UI在每个按钮获得缩略图后更新?直到整个方法完成,它才会更新。这些按钮已经被添加到UIScrollView中。

(LotsGridButton is just a UIButton with some extra properties.)

(LotsGridButton只是一个带有一些额外属性的UIButton。)

- (void)fetchThumbnails {
    CCServer* server = [[CCServer alloc] init];
    for (int i=0; i<[buttons count]; i++) {
        LotsGridButton* button = [buttons objectAtIndex:i];     
        if (button.lot.thumbnail) continue;
        // load the thumbnail image from the server
        button.lot.thumbnail = [server imageWithPath:button.lot.thumbnailURL];
        [button setImage:button.lot.thumbnail forState:UIControlStateNormal];
    }
    [server release];
}

2 个解决方案

#1


5  

In place of setImage:forState:, take a look at the performSelectorOnMainThread: method, e.g.:

代替setImage:forState:,请看performSelectorOnMainThread:方法,例如:

[myButton performSelectorOnMainThread:@selector(setThumbnail:) withObject:[server imageWithPath:myButton.lot.thumbnailURL] waitUntilDone:NO];

#2


3  

I've no experience with the iPhone but in Cocoa in general you're supposed to update the UI only from the main thread.

我没有使用iPhone的经验,但是在Cocoa中,你只能从主线程更新UI。

From a different thread you can execute code in the main thread by using NSObject's:

通过使用NSObject的:

performSelectorOnMainThread:withObject:waitUntilDone:

#1


5  

In place of setImage:forState:, take a look at the performSelectorOnMainThread: method, e.g.:

代替setImage:forState:,请看performSelectorOnMainThread:方法,例如:

[myButton performSelectorOnMainThread:@selector(setThumbnail:) withObject:[server imageWithPath:myButton.lot.thumbnailURL] waitUntilDone:NO];

#2


3  

I've no experience with the iPhone but in Cocoa in general you're supposed to update the UI only from the main thread.

我没有使用iPhone的经验,但是在Cocoa中,你只能从主线程更新UI。

From a different thread you can execute code in the main thread by using NSObject's:

通过使用NSObject的:

performSelectorOnMainThread:withObject:waitUntilDone: