NSOperationqueue i want to block main thread
i want to block the main thread until something else is done in the background.
i used:
result=[self performSelectorInBackground:@selector(calculate:) withObject:expression];
just bellow this line I am using result:
[self use:result];
i dont want to use result until it is available. to achieve this I implemented
-calculate:
{
[[(AppDelegate *)[[UIApplication sharedApplication] delegate] queue] waitUntilAllOperation开发者_JAVA技巧sAreFinished];
calculating result...
}
and still, the result is used before it is calculated. so, i didnt block the main thread. pls help me do that.
thanks
You don't want to block the main thread; it will prevent users from using the UI.
What you want is to use the result obtained in the background once it's ready.
One method is to call -use:
at the end of the method called in the background: you define
-(void)calculate:(NSString*)input
{
.... do the calculation ...
[self performSelectorOnMainThread:@selector(use:) withObject:result];
}
then you just call from the main thread
[self performSelectorInBackground:@selector(calculate:) withObject:expression];
This way, you can achieve what you want without blocking the main thread.
By the way, -performSelectorInBackgronud
has nothing to do with NSOperationQueue
. So [queue waitUntilAllOperationsAreFinished]
doesn't wait the execution of the method invoked by -performSelectorInBackground
.
And in any case, you shoudln't call waitUntilAllOperationAreFinished
unless absolutely necessary.
To know when an NSOperation
is done, you KVC the property isFinished
. See the NSOperation reference.
Yuji has the correct answer that will stop your user interface from freezing.
However, if you really do want the main thread to block, it's pointless farming the calculation out to another thread. Just do it on the main thread. i.e.
result = [self calculate: expression];
That is guaranteed to "block" the current thread until it is done. If executed on the main thread, it will "block" the main thread.
精彩评论