2011-08-19 55 views
0

在新线程结束时调用主线程将结果应用于UI是否很常见?我们不能应用“分离”线程的结果吗?例如,在示例代码ListAdder,我们使用:performElementInBackground之后调用performSelectorOnMainThread?

[self performSelectorInBackground:@selector(threadRecalculateNumbers:) withObject:immutableNumbers]; 

,并在功能上,我们再回到主线:

[self performSelectorOnMainThread:@selector(threadRecalculateDone:) withObject:totalStr waitUntilDone:NO]; 

和功能:

- (void)threadRecalculateDone:(NSString *)result 
{ 
    // The user interface is adjusted by a KVO observer on recalculating. 
    self.formattedTotal = result; 
    self.recalculating = NO; 
} 

谢谢

Paul

+0

(这真的很难看出你的问题是什么......) – Infinite

+1

“我们不能把我们的结果应用到”分离“线程吗?”不,用户界面不能从主线程以外的地方更新。 UIKit不是线程安全的。 – albertamg

+0

@albertamg:感谢albert,所以我们在创建分离线程后总是调用主线程是有道理的。你能作为一个职位做出答案吗?非常感谢 – Paul

回答

3

难道我们不能应用我们从“分离”线程得到的结果吗?

不,用户界面无法从主线程以外更新。一般而言,UIKit is not thread-safe.

大部分UIKit类只能在 应用程序的主线程中使用。对于从UIResponder派生的类 或者涉及以任何方式操纵应用程序的用户界面的情况尤其如此。

这就是为什么常见的做法是在后台执行长时间运行的任务,然后调用performSelectorOnMainThread来更新UI。

虽然beginning with iOS 4.0,绘制到UIKit中的图形上下文是线程安全的。具体而言,访问和操作当前的图形堆栈,绘制图像和字符串,以及从辅助线程使用颜色和字体对象。

相关问题