UIActivityIndicatorView will not stop

I play with some JSON parsing in iOS, and I wanted to add a counter, this works fine, but I can't stop the counter, and I would like to understand why.

[spinner stopAnimating] is called in the async block, and I believe that the problem is maybe because I can not call the method on the spinner in the block? I registered spinner obj, and the output is:

 <UIActivityIndicatorView: 0x76905f0; frame = (150 230; 20 20); layer = <CALayer: 0x768ffb0>> 

Maybe someone can make me understand how to deal with these asynchronous methods in objective-c. I am an absolute beginner.

Code:

 - (void)viewDidLoad{ [super viewDidLoad]; UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; spinner.center = CGPointMake(160, 240); [self.view addSubview:spinner]; [spinner startAnimating]; dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; NSLog(@"loans: %@", spinner); [spinner stopAnimating]; }); } 
+4
source share
3 answers

Never again (never!) Talk to the interface in the background thread. What you want is to return to the main thread - as you correctly suspect. This is frivolous:

 [spinner startAnimating]; dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL]; // ... do other stuff in the background dispatch_async(dispatch_get_main_queue(), ^{ [spinner stopAnimating]; }); }); 

However, using performSelectorOnMainThread:withObject:waitUntilDone: with waitUntilDone:YES also incorrect (or at least a very bad smell), since you should not block the background thread. Just call the method right here in the background thread (if it does not touch the interface), and when the result returns, it returns.

+8
source

also call removeFromSuperview method after stopAnimating

  [spinner stopAnimating]; [spinner removeFromSuperview]; 
+1
source

UIKit calls can only be made in the main thread. Try the following:

 dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL:kLatestKivaLoansURL]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; NSLog(@"loans: %@", spinner); dispatch_async(dispatch_get_main_queue(), ^{ [spinner stopAnimating]; }); }); 
0
source

All Articles