[英]display text during IBAction in objective-c
我有一些代码,如下所示:
- (IBAction)startButtonPressed:(id)sender {
statusText.text = @"Processing...";
//here I do a bunch of calculations
//display calculated data
statusText.text = [[NSString alloc] initWithFormat:@"coefficient: %.4f",
[[coefficientEstimatesR objectAtIndex:0] doubleValue]];
}
我所做的计算大约需要17秒,因此我想在完成时显示“正在处理”一词。 但是,运行此命令时,从不显示“处理中”,仅显示计算出的数据。
任何想法如何做到这一点将不胜感激。 谢谢!
不要在GUI线程中进行任何处理,不要花费一秒钟,尤其是花费17秒时。 使用GCD使卸载任务变得微不足道:
- (IBAction)startButtonPressed:(id)sender {
statusText.text = @"Processing...";
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//here I do a bunch of calculations
dispatch_async(dispatch_get_main_queue(), ^{
//display calculated data
statusText.text = [[NSString alloc] initWithFormat:@"coefficient: %.4f",
[[coefficientEstimatesR objectAtIndex:0] doubleValue]];
});
});
}
但是,运行此命令时,从不显示“处理中”,仅显示计算出的数据。
那是因为绘图发生在主线程上。 如果占用主线程进行计算,则将阻止其他所有可能发生的事情,包括绘制状态文本。
而是设置状态文本,启动后台线程(或将块分配到队列等),并尽快从操作方法中返回。 计算完成后,让后台线程(或块)在主线程上调用方法,以便您可以再次更改状态文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.