如何在延迟之前添加延迟
在正常的obj-c或cocos2d中有没有在if-else
块内延迟的方法? 像如何在延迟之前添加延迟
if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
[self addChild:circle0];
//wait two seconds
//perform another task
}
只是一个简单的滞后两个任务之间的等待时间,或拖延行动。有没有简单的方法来做到这一点?
可以使用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
}
有很多方法可以做到这一点。我会用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;
});
}
你不应该再使用'dispatch_get_current_queue()'。它已被弃用,并不完全安全。如果您需要对队列进行具体说明,则应该传递它,或者应该将其定义为发生在非特定队列或主队列中。 –
这工作,但作为@JasonCoco状态已弃用,我将与用户#######代替。 –
只有'dispatch_get_current_queue'已被弃用。其他一切仍然有效。就像@JasonCoco所说的,只需传递任何其他队列而不是'dispatch_get_current_queue'。 – creker
中的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];
我想它虽然 –
它没有多大的差别同样的方法执行里面,所以如果你想这样做的原因的布局,我能理解,但代码非常简单,并且不难遵循。 – Hacker
如果你不喜欢这种拖延行动的方法,试试克里克的答案。如果你这样做,我会建议查看苹果关于dispatch_get_current_queue()的文档:http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_get_current_queue.3.html – Hacker