问题
Please consider the following pieces of code:
In the first one i call a function which creates an animation. i do that with a certain time interval:
start:;
[self animationMethod];
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
//sleep(3);
goto start;
In the second one i create an animation
- (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);
}
and the third one is a delegate method which i use to check everything is going on ok:
- (void)animationDidStart:(CAAnimation *)anim
{
NSLog(@"ANIMATION DID START");
}
So when i use NSRunLoop
it works all right, the delegate method is called, but if i try to use with sleep(3)
function then the delegate method doesn't get called.
My questions:
1) Can you please explain the difference between NSRunLoop and sleep()? Why the delegate method isn't called when sleep() is used?
2) Maybe there is a third possible method which is better in usage?
回答1:
NSRunLoop is better because it allows the runloop to respond to events while you wait. If you just sleep your thread your app will block even if events arrive (like the network responses you are waiting for).
来源:https://stackoverflow.com/questions/9819004/difference-in-usage-of-function-sleep-and-nsrunloop-currentrunloop-rununtil