How to write lambda methods in Objective-C?

后端 未结 3 1355
悲哀的现实
悲哀的现实 2021-01-29 23:45

How to write lambda methods in Objective-C ?

3条回答
  •  不要未来只要你来
    2021-01-29 23:59

    OS X 10.6 introduced blocks. See AlBlue's answer for examples.

    If you're not using Snow Leopard, you can get something close to function composition using various other features.

    Example using C function pointers:

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

    Example using the command pattern:

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

    Example using a selector:

    @interface SaySomething : NSObject {
    }
    - (void) sayHello;
    @end
    
    @implementation SaySomething
    - (void) sayHello {
        NSLog(@"Hello!");    
    }
    @end
    
    void doSomethingTwice(id 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;
    }
    

提交回复
热议问题