show spinner and remove it in the same block

clankill3r picture clankill3r · May 13, 2013 · Viewed 15.9k times · Source

In a method that can take up to several seconds i have:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
spinner.color = [UIColor blueColor];
[spinner startAnimating];
[_mapViewController.view addSubview:spinner];

// lots of code

[spinner removeFromSuperview];

The spinner doesn't show up. Probably since the screen doesn't get update at that time. How can i get around this problem?

Answer

rmaddy picture rmaddy · May 13, 2013

Use GCD:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
spinner.color = [UIColor blueColor];
[spinner startAnimating];
[_mapViewController.view addSubview:spinner];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // lots of code run in the background

    dispatch_async(dispatch_get_main_queue(), ^{
        // stop and remove the spinner on the main thread when done
        [spinner removeFromSuperview];
    });
});