这不是完整的翻译,因为您的某些代码似乎丢失了(请参阅我上面的评论)..但这至少会给您一个起点:
var doSomething = function (callback) {
//some work
}
在 obj-c 中,这或多或少与 block 相同,因此您可以编写如下内容:
void (^doSomething)(id) = ^(callback) {
// some work
}
我不会解释语法,这就是上面链接的用途。由于 javascript 是松散类型的,并且您还没有指定回调的数据类型是什么。我将回调参数设置为 obj-c 中的通用 id,它可以代表任何类(包括块)
var start = function (interval, other, cb) {
setInterval(doSomething(function(result){
total = result + other
cb(total)
}), interval)
}
在这里,您基本上是在调用doSomething 并对结果回调应用一个任意函数,并且您在每interval 毫秒内进行一次调用。
在 Objective-c 中,您使用 NSTimer 来完成 setInterval 所做的事情。
NStimer 调用了一个选择器(即方法).. 所以我们只需要创建一个环绕我们的块的方法:
-(void)blockWrapper:(id)argument {
doSomething(argument);
}
然后我们使用该方法创建 NSTimer(请参阅下面的方法 here 的参考):
// here interval is in seconds, in your code it is in milliseconds
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@SEL(blockWrapper:)
userInfo:nil
repeats:YES];
更新:
所以现在我知道 start 是什么,我们基本上将其定义为(注意:这里我使用对上面原始 + scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 的修改。我从 here 借用修改。基本上而不是NSInterval 在选择器上运行,修改使其在块上运行。注意修改代码假定块没有参数。我会更改该代码并使其期望void(^blockName)((void)(^otherBlockname)(void)) 类型的参数..
- (void)start:(int)interval other:(int)other callback:(void)((^)(int total))callback {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:interval
repeats:YES
actions:doSomething(^(result) {
int total = result + other;
callback(total);
}
}
然后finally而不是
start(1000, 10, function(total){
console.log(total)
})
你会:
[start:1000 other:10 callback:^(total) {
NSLog(@"%d",total);
}];
最后的注释:上面的代码相当先进。我强烈建议您将每个部分都单独练习(即查看我上面引用的块文章..花点时间阅读它..块语法需要一段时间才能理解..它并不那么简单作为 javascript b/c 中的匿名函数,您必须非常具体地使用参数。同样,javascript 是一种松散类型的语言,而 obj-c 不是)。