如何在Objective-C中编写lambda方法?
发布于 2009-11-28 04:03:34
Objective-C中的lambda的概念现在被封装在Blocks的思想中,这相当于通过引用传递函数。当然,有争议的是,在C中已经有了函数指针的概念;块只是一种捕获本地状态的方法(即可以是闭包)。事实上,块也可以在其他C语言中使用(在Mac上)--有人建议将它们作为标准C语法的一部分。
下面是一个定义lambda将两个数字相乘的示例:
int (^mult)(int, int) = ^(int a, int b) { return a*b; };
第一部分声明了一个^int(int,int)
类型的变量,然后将其赋给λ表达式(也称为块),该表达式返回两个参数的倍数。然后,您可以传递该fn,在其他地方定义它等;您甚至可以在其他函数中使用它。
下面是一个定义函数的示例,当调用该函数时,将返回另一个函数:
multiplyBy = ^(int a) { return ^(int b) { return b*a; }; };
triple = multiplyBy(3);
请注意,您可以混合使用块和对象类型(通常使用id
作为对象类型),并且许多新的Objective-C对象数据结构都具有某种块级操作。GCD还使用块来传递任意事件;但是,请注意,GCD也可以与函数指针一起使用。
发布于 2009-06-03 11:42:12
OS X 10.6引入了块。参见AlBlue's answer for examples。
如果你没有使用Snow Leopard,你可以使用其他各种特性来获得接近于函数组合的东西。
使用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;
}
使用选择器的示例:
@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;
}
发布于 2009-06-03 11:49:30
我在NSConference听到AndréPang谈到下一个版本的Objective-C将如何引入块。
这应该允许函数式编程。
编辑:自从Snow Leopard发布以来,情况确实如此。Objective-C现在有了Blocks。
https://stackoverflow.com/questions/943992
复制相似问题