简体   繁体   中英

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. 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. Using GCD makes offloading the task trivial:

- (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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