简体   繁体   English

在Objective-C的IBAction期间显示文本

[英]display text during IBAction in objective-c

I have some code as shown below: 我有一些代码,如下所示:

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

The calculations that I do take about 17s, so I'd like to display the word "processing" while this is being done. 我所做的计算大约需要17秒,因此我想在完成时显示“正在处理”一词。 However, when I run this, "processing" is never displayed, only the calculated data is displayed. 但是,运行此命令时,从不显示“处理中”,仅显示计算出的数据。

Any ideas on how to do this would be appreciated. 任何想法如何做到这一点将不胜感激。 Thanks! 谢谢!

Do not do any processing in the GUI thread, not when it takes one second, and especially not when it takes 17 seconds. 不要在GUI线程中进行任何处理,不要花费一秒钟,尤其是花费17秒时。 Using GCD makes offloading the task trivial: 使用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]];
        });
    });
}

However, when I run this, "processing" is never displayed, only the calculated data is displayed. 但是,运行此命令时,从不显示“处理中”,仅显示计算出的数据。

That's because drawing happens on the main thread. 那是因为绘图发生在主线程上。 If you tie up the main thread doing your calculations, you'll block everything else that should be happening including drawing the status text. 如果占用主线程进行计算,则将阻止其他所有可能发生的事情,包括绘制状态文本。

Instead, set your status text, fire off a background thread (or dispatch a block to a queue, etc.), and return from your action method as quickly as you can. 而是设置状态文本,启动后台线程(或将块分配到队列等),并尽快从操作方法中返回。 Have the background thread (or block) call a method on the main thread when the calculation is done so that you can change the status text again. 计算完成后,让后台线程(或块)在主线程上调用方法,以便您可以再次更改状态文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM