Reputation: 447
I want to pause the execution of while loop for 200 milliseconds.I have used [NSThread sleepForTimeInterval:0.2] ,It's working fine for me but, I want to know what are the alternative ways to pause execution of while loop?
Upvotes: 2
Views: 1318
Reputation: 122391
If it's working fine then no problem, however if you are doing something in the thread that needs the runloop (i.e. NSTimer
or NSURLRequest
in async mode) then you need to run the runloop, so this would be required:
(tested)
+ (void)runRunLoopForTimeInterval:(NSTimeInterval)timeInterval {
NSDate *stopTime = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
while ([stopTime compare:[NSDate date]] == NSOrderedDescending) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:stopTime];
}
}
and call it like this:
[SomeClass runRunLoopForTimeInterval:0.2];
EDIT Some assumptions:
Upvotes: 1
Reputation: 130102
Let's imagine we have a while
in the following form:
while (... condition ...) {
... doSomething ...;
if (... waitCondition ...) {
//I want to wait here
}
}
We will make it asynchronous, first by abstracting things into methods:
- (BOOL)condition {
//some condition, e.g.
return (self.counter > 5000);
}
- (void)doSomething {
//do something, e.g.
self.view.alpha = self.counter / 5000.0f;
self.counter++;
}
- (BOOL)waitCondition {
// some wait condition, e.g.
return ((self.counter % 100) == 0);
}
- (void)startWhile {
//init the state
self.counter = 0;
[self performWhile];
}
- (void)performWhile {
while ([self condition]) {
[self doSomething];
if ([self waitCondition]) {
[self performSelector:@selector(performWhile)
withObject:nil
afterDelay:0.2
inModes:@[NSDefaultRunLoopMode]];
}
}
}
Instead of using a global state in self
, you can also use a parameter with performWhile
.
Upvotes: 0