【问题标题】:How do I update the UI in the middle of this thread?如何在此线程中间更新 UI?
【发布时间】:2009-04-30 05:11:07
【问题描述】:

以下是在与我的应用程序主线程不同的线程中运行的代码块。如何在每个按钮获取缩略图后更新 UI?现在它不会更新,直到整个方法完成。按钮已添加到 UIScrollView。

(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];
}

【问题讨论】:

    标签: iphone objective-c cocoa-touch


    【解决方案1】:

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

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

    【讨论】:

    • 甜蜜!它起作用了,一旦我做了一个包装方法(因为 performSelector 只需要一个 arg 而 setImage:forState: 需要 2 个)。这是一般模式的一个实例,例如“更改主线程中的小部件,它会立即显示其更改”?
    • 至少在 iPhone 上,UI 更新发生在主线程上。您无法从后台线程可靠地更新小部件。因此,通过在执行 UI 更新的主线程上运行方法,您更有可能获得更快的 UI 更新。
    【解决方案2】:

    我没有使用 iPhone 的经验,但一般来说,在 Cocoa 中,您应该只从主线程更新 UI。

    您可以在不同的线程中使用 NSObject 执行主线程中的代码:

    performSelectorOnMainThread:withObject:waitUntilDone:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 2012-07-21
      • 2011-04-14
      • 2014-01-14
      相关资源
      最近更新 更多