Reputation: 113
I'm trying to make activity indicator while uploading files, so i've found a lot of solutions, but i guess i don't fully understand them, so my code look like this:
- (void) startSpinner {
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner setCenter:CGPointMake(self.view.frame.size.width/2.0, self.view.frame.size.height/2.0)];
[self.view addSubview:spinner];
[spinner startAnimating];
}
- (void)startSync {
[NSThread detachNewThreadSelector:@selector(startSpinner) toTarget:self withObject:nil];
// computations
[self.spinner stopAnimating];
}
So after i do [self startSync] activityIndicator appears, but after uploading it didn't stop. Also if i declare activity indicator somewhere else (not in the (void)startSpinner), for example in viewDidLoad, and only do [self startAnimating] it didn't appear at all. Please help me find out errors.
Upvotes: 2
Views: 1431
Reputation: 69
It happens become you declare local variable spinner inside startSpinner method.
When you call self.spinner, it does not affect the local variable spinner you declared inside startSpinner method. You have 2 separate variable with same name.
You have to declare
spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
Upvotes: 1
Reputation: 14304
You're performing UI operations on a thread that isn't the main thread.
You should never call detachNewThreadSelector
with a selector that performs UI related tasks.
A better, more understandable way to do this is:
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicator startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Perform lengthy operations
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicator stopAnimating];
});
});
});
Also, if you choose to work with selectors - make sure your UIActivityIndicatorView is declared outside the scope of the method.
Upvotes: 4
Reputation: 1814
- (void) startSpinner
{
self.spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner setCenter:CGPointMake(self.view.frame.size.width/2.0, self.view.frame.size.height/2.0)];
[self.view addSubview:spinner];
[spinner startAnimating];
}
- (void)startSync
{
[NSThread detachNewThreadSelector:@selector(startSpinner) toTarget:self withObject:nil];
// computations
[self.spinner performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
self.spinner = nil;
}
Upvotes: 1