How to perform Callbacks in Objective-C

后端 未结 5 1354
无人及你
无人及你 2020-11-27 09:09

How to perform call back functions in Objective-C?

I would just like to see some completed examples and I should understand it.

5条回答
  •  猫巷女王i
    2020-11-27 09:46

    For completeness, since StackOverflow RSS just randomly resurrected the question for me, the other (newer) option is to use blocks:

    @interface MyClass: NSObject
    {
        void (^_completionHandler)(int someParameter);
    }
    
    - (void) doSomethingWithCompletionHandler:(void(^)(int))handler;
    @end
    
    
    @implementation MyClass
    
    - (void) doSomethingWithCompletionHandler:(void(^)(int))handler
    {
        // NOTE: copying is very important if you'll call the callback asynchronously,
        // even with garbage collection!
        _completionHandler = [handler copy];
    
        // Do stuff, possibly asynchronously...
        int result = 5 + 3;
    
        // Call completion handler.
        _completionHandler(result);
    
        // Clean up.
        [_completionHandler release];
        _completionHandler = nil;
    }
    
    @end
    
    ...
    
    MyClass *foo = [[MyClass alloc] init];
    int x = 2;
    [foo doSomethingWithCompletionHandler:^(int result){
        // Prints 10
        NSLog(@"%i", x + result);
    }];
    

提交回复
热议问题