gpt4 book ai didi

cocoa - 线程 NSProgressIndicator 问题

转载 作者:行者123 更新时间:2023-12-03 16:51:04 26 4
gpt4 key购买 nike

我试图弄清楚如何使用辅助线程更新 UI 中不确定的 NSProgressIndicator,而主线程则执行一些繁重的工作,就像数十个应用程序所做的那样。此代码段基于 Apple 的“Trivial Threads”示例使用分布式对象 (DO):

// 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-C 的新手,非常感谢任何有关这方面的帮助。

最佳答案

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

关于cocoa - 线程 NSProgressIndicator 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1393456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com