coc*_*der 3 multithreading objective-c nsprogressindicator
我在我的主线程中使用NSProgressIndicator来更新进度,因为我运行了整个方法.现在,当我最终从另一个类文件调用一个对象,并等待该对象返回到我的主线程的值时,我注意到NSProgressIndicator将消失.我知道这是因为主线程被阻塞,直到我从另一个对象获得返回值.
所以我的问题是在主线程中更新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
}
Run Code Online (Sandbox Code Playgroud)
当调用另一个对象时,我注意到确定的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];});
});
}
Run Code Online (Sandbox Code Playgroud)
(是的,这会导致队列保留self,但这样就可以了,因为self没有保留队列.)
| 归档时间: |
|
| 查看次数: |
3246 次 |
| 最近记录: |