objective-clistenerobjective-c-blockscompletion-block

how to execute completion block from another method in objective-c?


Is it impossible to get completion block success then data received from another method?

@property myCompletion;

// I have first call listeners, i can't add this in to "createOrderWithsuccess"

-(void)listeners {
    [[SocketIOManager sharedInstance].socket on:@"someAction" callback:^(NSArray* data, SocketAckEmitter* ack) {
        // data received
        myCompletion(data);

    }];

}

// this will be called <del>first</del> later
- (void)createOrderWithsuccess:^(NSArray *data) {
    // but it has to wait then data will be received  
    myCompletion = success;
 }

Solution

  • It's a bit hard to understand what you are looking for, but this might be it. This is how I handle Completion callbacks in my app:

    @import Foundation;
    
    typedef void (^CompletionBlock)(NSArray *data);
    
    @interface TheClass()
    
    @property (nonatomic, copy) CompletionBlock *myCompletion;
    
    @end
    
    @implementation TheClass()
    
    // ....
    
    
    - (void) createOrderWithsuccess:(CompletionBlock)success {
        _myCompletion = success;
    }
    
    -(void)listeners {
        [[SocketIOManager sharedInstance].socket on:@"someAction" callback:^(NSArray* data, SocketAckEmitter* ack) {
            // data received
            _myCompletion(data);
    
        }];
    }
    
    // Alternatively, breaking possible retain cycles
    -(void)listeners {
        __weak TheClass *weakSelf = self;
        [[SocketIOManager sharedInstance].socket on:@"someAction" callback:^(NSArray* data, SocketAckEmitter* ack) {
            // data received
            if(weakSelf.myCompletion) weakSelf.myCompletion(data);
        }];
    }
    

    The typedef should be in the .h file so that both this class and the one calling createOrderWithsuccess: knows about it.