我试图弄清楚如何使用辅助线程更新UI中的不确定NSProgressIndicator,而主线程执行一些繁重的任务,就像许多应用程序do.This片段基于苹果使用分布式对象(DO‘s)的“琐碎线程”示例一样:
// In the main (client) thread...
- (void)doSomethingSlow:(id)sender
{
[transferServer showProgress:self];
int ctr;
for (ctr=0; ctr <= 100; ctr++)
{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
NSLog(@"running long task...");
}
}
// In the secondary (server) thread...
- (oneway void)showProgress:(Controller*)controller
{
[controller resetProgressBar];
float ticks;
for (ticks=0; ticks <= 100; ticks++)
{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
[controller updateProgress:ticks];
NSLog(@"updating progress in UI...");
}
}然而,不幸的是,我无法让两个线程同时运行。要么二级线程运行,主线程等待它完成,要么主线程运行,然后是辅助线程--但不是同时运行这两个线程。
即使我传递一个指向服务器线程的指针,并要求它直接更新进度条(而不调用主线程),这也没有什么区别。看起来,一旦主线程进入这样的循环,它就会忽略发送给它的所有对象。我还是一个在Obj公司的新手,我非常感谢你在这方面的任何帮助。
发布于 2009-09-08 11:33:26
AppKit根本不是线程安全的。您必须从主线程更新UI,否则会发生各种疯狂的事情(否则就无法工作)。
最好的方法是在辅助线程上完成工作,在需要更新UI时调用主线程:
-(void)doSomethingSlow:(id)sender {
[NSThread detachNewThreadSelector:@selector(threadedMethod) toTarget:self withObject:nil];
// This will return immediately.
}
-(void)threadedMethod {
int ctr;
for (ctr=0; ctr <= 100; ctr++) {
NSLog(@"running long task...");
[self performSelectorOnMainThread:@selector(updateUI)];
}
}
-(void)updateUI {
// This will be called on the main thread, and update the controls properly.
[controller resetProgressBar];
}发布于 2009-09-08 11:28:09
您可能需要尝试切换线程。通常,UI更新和用户输入将在主线程上处理,而次要线程则会保留繁重的任务。
https://stackoverflow.com/questions/1393456
复制相似问题