AlB*_*lue 89

Objective-C中lambda的概念现在用Blocks的概念封装,这相当于pass-by-reference函数.当然,可以说有一个已经在C中已经有了函数指针的想法; 块只是一种捕获局部状态的方式(即可以是闭包).实际上,块也可以用在其他C语言中(在Mac上) - 有一个建议使它们成为标准C语法的一部分.

这是一个定义lambda以将两个数相乘的示例:

int (^mult)(int, int) = ^(int a, int b) { return a*b; };
Run Code Online (Sandbox Code Playgroud)

第一部分声明一个类型的变量,^int(int,int)然后将它分配给lambda表达式(aka block),该表达式返回其两个参数的倍数.然后你可以传递那个fn,在其他地方定义它等; 你甚至可以在其他功能中使用它.

这是一个定义函数的示例,在调用时,它返回另一个函数:

multiplyBy = ^(int a) { return ^(int b) { return b*a; }; };
triple = multiplyBy(3);
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用对象类型混合块(通常使用id对象类型),并且许多新的Objective-C对象数据结构具有某种块级操作.GCD还使用块来传递任意事件; 但请注意,GCD也可以与函数指针一起使用.

  • ObjC块类似于Smalltalk块,但在Objective C中不清楚如何定义,实现,传递,接受和调用任意类型的块. (2认同)

Wil*_*ris 28

OS X 10.6引入了块.有关示例,请参阅AlBlue的答案.

如果你没有使用Snow Leopard,你可以使用各种其他功能获得接近功能组合的东西.

使用C函数指针的示例:

void sayHello() {
    NSLog(@"Hello!");
}

void doSomethingTwice(void (*something)(void)) {
    something();
    something();
}

int main(void) {
    doSomethingTwice(sayHello);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用命令模式的示例:

@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;
}
Run Code Online (Sandbox Code Playgroud)

使用选择器的示例:

@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;
}
Run Code Online (Sandbox Code Playgroud)