如何在Objective-C中编写lambda方法?
如何在Objective-C中编写lambda方法?
在Objective-C中,lambda的概念现在用Blocks来封装,它们是按引用传递函数的等效形式。当然,在C语言中,使用函数指针的想法已经具有了这个功能;Blocks只是一种也可以捕获本地状态(即可成为闭包)的方式。事实上,Blocks也可以在其他C语言中使用(在Mac上)- 提议使其成为标准C语法的一部分。
以下是定义一个lambda将两个数字相乘的示例:
int (^mult)(int, int) = ^(int a, int b) { return a*b; };
首先声明了一个变量,类型为^int(int,int)
,然后将其赋值给lambda表达式(也称为块),该表达式返回它的两个参数的乘积。然后可以传递此函数,定义它在其他地方等等;甚至可以在其他函数中使用它。
下面是一个定义函数的示例,当调用时,它返回另一个函数:
multiplyBy = ^(int a) { return ^(int b) { return b*a; }; };
triple = multiplyBy(3);
请注意,您可以将块与对象类型混合使用(通常使用id
作为对象类型),许多新的Objective-C对象数据结构也具有某种块级操作。 GCD还使用块来传递任意事件;但是,请注意,GCD也可以与函数指针一起使用。
OS X 10.6引入了blocks。请参见AlBlue的答案以获取示例。
如果您没有使用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;
}
myBlock = ^( int number )
{
return [ NSString stringWithFormat: @"Passed number: %i", number ];
};
NSString * ( ^ myBlock )( int );