Working with some code, I'm coming across run loops, which I'm new to, inside NSOperation
s.
The NSOperation
s are busy downloading data - and whilst they are busy, there is code to wait for the downloads to complete, in the form of NSRunLoop
s and thread sleeping.
This code in particular is of interest to me:
while (aCertainConditionIsTrue && [self isCancelled]==NO) {
if(![[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]){
[NSThread sleepForTimeInterval:1.0];
}
}
I've read about the run loops, and runMode:beforeDate:
will wait for an input source or a timeout. Although I'm not 100% what counts as an input souce.
On the first execution of this it always returns NO and hits the sleepForTimeInterval:
. Is this bad?
In a particular utility class, it's hitting the sleepForTimeInterval:
a lot - once for each thread - which significantly hurts the performance.
Any better solutions for this, or advice?
Sleeping locks up the thread. Perhaps you change your code to use performSelector:withObject:afterDelay. That way your thread can continue to run.
...
done = NO;
[self checkDoneCondition:nil];
...
- (void)checkDoneCondition:(id)object {
if (aCertainConditionIsTrue && [self isCancelled]==NO) {
if(...) {
[self performSelector:@selector(checkDoneCondition:) withObject:[con error] afterDelay:1.0];
} else {
done = YES;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With