I am trying to monitor a thread that i set running in the background. I need to be alerted when it is finished executing.
- (IBAction) btnGreaterTen_clicked :(id)sender{
self.searchDistance = [NSNumber numberWithDouble : 10];
CGRect frame = CGRectMake (120.0, 185.0, 80, 80);
activity = [[UIActivityIndicatorView alloc] initWithFrame: frame];
activity.activityIndicatorViewStyle = U开发者_如何学GoIActivityIndicatorViewStyleGray;
[navigationUpdateFromDetail.window addSubview: activity];
[activity startAnimating];
thread = [[NSThread alloc] init];
[thread start];
[self performSelectorInBackground: @selector (getSetDisplay) withObject:nil];
if(thread.isFinished == YES){
[activity stopAnimating];
}
}
The above code what i have after trying different set up in order to achieve the end result. I am trying to animate the UIActivityIndicator while I use that method "getSetDisplay" to grab information from the net.
The function is good, but the Activity indicator was not coming up. I was told that i needed to run the process on a background thread and the animation on the main thread. My problem now is how do I monitor for when this process is done to stop the activity indicator. thank you in advance
You should consider the problem from a different angle: you should let your "main thread" continue to run, and let your "secondary thread" call a selector on the main thread when it is done doing work.
To accomplish this, you should use the performSelectorOnMainThread
method, and call it from your secondary thread. Its prototype is - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
. You should put your "finishing" code in a method, and then do something like:
[self performSelectorOnMainThread:@selector(doneDoingWork) withObject:nil waitUntilDone:NO];
Thank you guys. I finally got a solution that worked thanks to Mike and his above comment.
- (IBAction) btnGreaterTen_clicked :(id)sender{
self.searchDistance = [NSNumber numberWithDouble : 10];
[activity startAnimating];
NSLog(@" search value after change %@", [searchDistance description]);
[self performSelectorInBackground: @selector (getSetDisplay) withObject: nil];
}
I started the activity indicator on with the "[activity startAnimating]" which runs on the main thread. Then i started my method on a background thread with the "performSelectorInBackground". And at the end of my "getSetDisplay" method, i placed the following statement.
[activity performSelectorOnMainThread: @selector (stopAnimating) withObject:nil waitUntilDone:NO];
This is just another way to say [activity stopAnimating], which is working on the main thread.
Thank you to all that responded.
精彩评论