Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show spinner and remove it in the same block

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?

like image 450
clankill3r Avatar asked May 13 '13 19:05

clankill3r


1 Answers

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];
    });
});
like image 68
rmaddy Avatar answered Sep 21 '22 19:09

rmaddy