如何在Objective-C中编写lambda方法?

如何在Objective-C中编写lambda方法?

Objective-C中lambda的概念现在被封装在块的思想中,这等价于通过引用函数。 当然,可以说C中已经有了函数指针的概念, 块只是一种捕获本地状态的方式(即可以closures)。 实际上,块也可以在其他C语言中使用(在Mac上) – 有一个build议是使它们成为标准C语法的一部分。

下面是一个定义一个lambda来将两个数字相乘的例子:

int (^mult)(int, int) = ^(int a, int b) { return a*b; }; 

第一部分声明一个types为^int(int,int)的variables,然后将其赋值给返回其两个参数的倍数的lambdaexpression式(aka block)。 然后你可以通过这个fn,在其他地方定义它。 你甚至可以在其他function中使用它。

这里是定义一个函数的例子,当被调用时,函数返回另一个函数:

 multiplyBy = ^(int a) { return ^(int b) { return b*a; }; }; triple = multiplyBy(3); 

请注意,可以将块与对象types混合(通常使用id作为对象types),并且许多新的Objective-C对象数据结构具有某种块级别的操作。 GCD也使用块来传递任意事件; 但是请注意,GCD也可以用于函数指针。

OS X 10.6引入了块。 查看AlBlue的答案的例子 。

如果您不使用雪豹,您可以使用各种其他function获得与function组合相近的function。

使用C函数指针的示例:

 void sayHello() { NSLog(@"Hello!"); } void doSomethingTwice(void (*something)(void)) { something(); something(); } int main(void) { doSomethingTwice(sayHello); return 0; } 

使用命令模式的示例:

 @protocol Command <NSObject> - (void) doSomething; @end @interface SayHello : NSObject <Command> { } @end @implementation SayHello - (void) doSomething { NSLog(@"Hello!"); } @end void doSomethingTwice(id<Command> command) { [command doSomething]; [command doSomething]; } int main(void) { SayHello* sayHello = [[SayHello alloc] init]; doSomethingTwice(sayHello); [sayHello release]; return 0; } 

使用select器的示例:

 @interface SaySomething : NSObject { } - (void) sayHello; @end @implementation SaySomething - (void) sayHello { NSLog(@"Hello!"); } @end void doSomethingTwice(id<NSObject> obj, SEL selector) { [obj performSelector:selector]; [obj performSelector:selector]; } int main(void) { SaySomething* saySomething = [[SaySomething alloc] init]; doSomethingTwice(saySomething, @selector(sayHello)); [saySomething release]; return 0; } 

我听说NSConference的AndréPang谈到如何在下一个版本的Objective-C中引入块。

这应该允许function编程。

编辑:自从雪豹被释放后,情况确实如此。 Objective-C现在有块 。