Mar*_*lor 3 syntax function objective-c cocos2d-iphone ios
我正在开发一个带有Cocos2D的iOS应用程序,而且我遇到了很多需要稍微延迟的事情,所以我使用了一行代码:
[self scheduleOnce:@selector(do_something) delay:10];
Run Code Online (Sandbox Code Playgroud)
发生的事情do_something只是一行代码.有没有办法让我在我安排它的那一行定义函数?
当我以前用jQuery编程时,这与我想要实现的类似:
$("a").click(function() {
alert("Hello world!");
});
Run Code Online (Sandbox Code Playgroud)
看看函数()是如何定义的?有没有办法在Objective-C中做到这一点?还有,这有名字吗?为了将来的搜索?因为我发现这很难解释.
您可以dispatch_after在一定时间后用于执行块.
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
/* code to be executed on the main queue after delay */
});
Run Code Online (Sandbox Code Playgroud)
我会把它称为时间调度块.
编辑:如何只发送一次.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
/* code to be executed once */
});
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
/* code to be executed on the main queue after delay */
})
});
Run Code Online (Sandbox Code Playgroud)