我想暂停执行while循环200毫秒。我已经使用[NSThread sleepForTimeInterval:0.2],它对我来说很好但是,我想知道暂停执行while循环的替代方法是什么?
答案 0 :(得分:1)
如果它工作正常然后没问题,但是如果你在需要runloop的线程中做某事(即在异步模式下是NSTimer
或NSURLRequest
)那么你需要运行< / em> runloop,所以这是必需的:
(测试)
+ (void)runRunLoopForTimeInterval:(NSTimeInterval)timeInterval {
NSDate *stopTime = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
while ([stopTime compare:[NSDate date]] == NSOrderedDescending) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:stopTime];
}
}
并将其称为:
[SomeClass runRunLoopForTimeInterval:0.2];
编辑一些假设:
答案 1 :(得分:0)
让我们假设我们有以下形式的while
:
while (... condition ...) {
... doSomething ...;
if (... waitCondition ...) {
//I want to wait here
}
}
我们将把它变为异步,首先将事物抽象为方法:
- (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]];
}
}
}
您可以在self
中使用参数,而不是在performWhile
中使用全局状态。