2013-05-18 129 views
1

在正常的obj-c或cocos2d中有沒有在if-else塊內延遲的方法? 像如何在延遲之前添加延遲

if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord]) 
{ 
    [self addChild:circle0]; 
    //wait two seconds 
    //perform another task 
} 

只是一個簡單的滯後兩個任務之間的等待時間,或拖延行動。有沒有簡單的方法來做到這一點?

回答

2

可以使用performSelector: withObject: afterDelay:方法延遲任務:

if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord]) 
{ 
    [self addChild:circle0]; 
    //wait two seconds 
    [self performSelector:@selector(continueTask) withObject:nil afterDelay:2.0]; 

} 

而在選擇方法:

-(void)continueTask 
{ 
    //perform another task 
} 
+0

我想它雖然 –

+0

它沒有多大的差別同樣的方法執行裏面,所以如果你想這樣做的原因的佈局,我能理解,但代碼非常簡單,並且不難遵循。 – Hacker

+0

如果你不喜歡這種拖延行動的方法,試試克里克的答案。如果你這樣做,我會建議查看蘋果關於dispatch_get_current_queue()的文檔:http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_get_current_queue.3.html – Hacker

3

有很多方法可以做到這一點。我會用GCD

if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord]) 
{ 
    [self addChild:circle0]; 
    //wait two seconds 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{ 
     //perform another task; 
    }); 
} 
+1

你不應該再使用'dispatch_get_current_queue()'。它已被棄用,並不完全安全。如果您需要對隊列進行具體說明,則應該傳遞它,或者應該將其定義爲發生在非特定隊列或主隊列中。 –

+0

這工作,但作爲@JasonCoco狀態已棄用,我將與用戶#######代替。 –

+0

只有'dispatch_get_current_queue'已被棄用。其他一切仍然有效。就像@JasonCoco所說的,只需傳遞任何其他隊列而不是'dispatch_get_current_queue'。 – creker

1

中的cocos2d裏面你還可以運行的節點就像一個行動,

[self runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2.0],[CCCallFunc actionWithTarget:self selector:@selector(anothertaks)],nil]]; 

進行選擇也將工作,但問題是,cocos2D上的所有調度得到暫停時該應用程序去背景,但另一方面執行選擇器仍然會計時,所以一段時間它創建任務,動畫等同步問題。

進行選擇:

[self performSelector:@selector(continueTask) withObject:nil afterDelay:2.0];