函数sleep()和[[NSRunLoop currentRunLoop] runUntilDate]的使用差异

And*_*kha 3 iphone sleep objective-c nsrunloop

请考虑以下代码:

在第一个中,我调用一个创建动画的函数.我以一定的时间间隔做到这一点:

start:;

[self animationMethod];

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
//sleep(3);

goto start;
Run Code Online (Sandbox Code Playgroud)

在第二个我创建一个动画

- (void)animationMethod
 {
  CAKeyframeAnimation *myAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
CGMutablePathRef curvedPath             = CGPathCreateMutable();

CGPathMoveToPoint(curvedPath, NULL, start.x, start.y);
CGPathAddCurveToPoint(curvedPath, NULL, fcp.x, fcp.y, scp.x , scp.y, end.x, end.y); 

myAnimation.path                = curvedPath;
myAnimation.duration            = flight_duration;
myAnimation.removedOnCompletion = NO;
myAnimation.delegate            = self;  
myAnimation.fillMode            = kCAFillModeForwards;

[myAnimation setValue:identifier forKey:@"id"];

[flyingBug addAnimation:myAnimation forKey:@"bug_flight"];

CGPathRelease(curvedPath);
 }
Run Code Online (Sandbox Code Playgroud)

第三个是委托方法,我用来检查一切正常:

- (void)animationDidStart:(CAAnimation *)anim
{

    NSLog(@"ANIMATION DID START");
}
Run Code Online (Sandbox Code Playgroud)

因此,当我使用NSRunLoop它工作正常时,调用委托方法,但如果我尝试使用sleep(3)函数,那么委托方法不会被调用.

我的问题:

1)你能解释一下NSRunLoop和sleep()之间的区别吗?为什么在使用sleep()时不调用委托方法?

2)也许第三种可能的方法更好用?

Kul*_*eep 8

NSRunLoop更好,因为它允许runloop在您等待时响应事件.如果你只是睡觉你的线程你的应用程序将阻止即使事件到达(如你正在等待的网络响应).