2012-03-22 100 views
2

請考慮下面的代碼段:差異睡眠功能的使用()和[[NSRunLoop currentRunLoop] runUntilDate]

在第一個我調用它創建的動畫的功能。我做到這一點與在一定的時間間隔:

start:; 

[self animationMethod]; 

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

goto start; 

在第二個我創建動畫

- (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); 
} 

,第三個是我使用來檢查一切都會上確定一個委託方法:

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

    NSLog(@"ANIMATION DID START"); 
} 

所以,當我使用NSRunLoop它的作品的所有權利,委託方法被調用,但如果我嘗試用sleep(3)功能使用,然後委託方法沒有得到召喚編輯。

我的問題:

1)能否請你解釋NSRunLoop和睡眠(之差)?爲什麼在使用sleep()時不調用委託方法?

2)也許有第三種方法更好的使用?

回答

7

NSRunLoop更好,因爲它允許runloop在等待時響應事件。如果你只是睡覺你的線程,即使事件到達,你的應用也會阻塞(就像你正在等待的網絡響應)。