iosobjective-casynchronouscallback

iOS: how to implement a shared method for two API callbacks returning the same result/error set


I am writing a client APP calling an API and processing the results in a a callback method.

The method is defined as follows:

//Current implementation

[_myAPIInterface dataByName:name withCallback:^(NSError *error, NSDictionary *result) {
        //Method body.. processing the results

        if (error) {
            return;
        }
        else{
            [self.activityIndicator stopAnimating];
        }
 }];

I would like to be able to define teh callBack block as a separate function that I can call so whenever I call the API as client passing different paramenters (e.g. by name, by age) I can pass the same block/method to process the results and avoid implementing it twice.

//Desired implementation/approach
[_myAPIInterface dataByName:name withCallback:^(NSError *error, NSDictionary *result) {
      [self sharedMethod:error :results];   
 }];

[_myAPIInterface dataByAge:age withCallback:^(NSError *error, NSDictionary *result) {
      [self sharedMethod:error :results];   
 }];

Solution

  • Yes, you can assign the block to a variable and pass that variable to each method.

    void (^callback)(NSError *, NSDictionary *) = ^(NSError *error, NSDictionary *result) {
        //Method body.. processing the results
    
        if (error) {
            return;
        }
        else {
            [self.activityIndicator stopAnimating];
        }
    };
    
    [_myAPIInterface dataByName:name withCallback:callback];
    [_myAPIInterface dataByAge:age withCallback:callback];