当我运行整个方法时,我在主线程中使用 NSProgressIndicator 来更新进度。现在,当我最终从不同的类文件调用一个对象,并等待该对象返回到我的主线程的值时,我注意到 NSProgressIndicator 将消失。我明白这是因为主线程被阻塞,直到我从另一个对象获得返回值。
所以我的问题是,在主线程中更新 UI 而不阻塞 UI 并让其他对象在后台运行并根据需要将值返回到主线程的推荐方法是什么。我知道如何使用块,但块操作不允许返回值。
我需要的是有助于这个伪代码的东西:
-(IBAction) main {
//Update progress indicator UI to show progress
//perform an call to another object from another class.
// wait till i get its return value.
//Update progress indicator UI to show progress
// Use this return value to do something.
//Update progress indicator UI to show progress
}
当调用另一个对象时,我注意到由于主线程被阻塞,我所确定的 NSProgressIndicator 完全消失了。谢谢。
您上面的代码不是正确的方法。自从main
永远不会返回,进度指示器永远不会更新。您必须快速返回主线程。
相反,您想要做的是设置一个后台块,在不同的点更新主线程上的进度指示器。因此,例如:
- (IBAction)start:(id)sender {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
dispatch_async(dispatch_get_main_queue(), ^{[self.progress setProgress:0];});
// Doing some stuff
dispatch_async(dispatch_get_main_queue(), ^{[self.progress setProgress:.25];});
// Doing more stuff
dispatch_async(dispatch_get_main_queue(), ^{[self.progress setProgress:.75];});
});
}
(是的,这会导致队列保留self
,但这里没问题,因为self
不保留队列。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)