Question

Using inheritance.

I have a child class that calls a method in the parent class that runs calls the server API.

-(IBAction)buttonPressed
{
    [self methodInParentClassThatCallsTheAPI:param];
    // This is where I would like the call back
     if (success from the server API) // do something with the UI
     else if (failure from the server API) // do so something else with the UI
}

Parent Class:

- (void)methodInParentClassThatCallsTheAPI:(NSString *)param
{
      //The method below calls the server API and waits for a response.  
      [someServerOperation setCompletionBlockWithSuccess:^(param, param){
        // Return a success flag to the Child class that called this method
      } failure:^(param, NSError *error){
        // Return a failure flag to the Child class that called this method
      }
}

How can I accomplish this with a block? Is there a better way to do this other than the block? Code example please

Was it helpful?

Solution

Create a completion block on methodInParentClass like this:

- (void)methodInParentClassThatCallsTheAPI:(NSString *)param completionBlock:(void (^)(BOOL success))completionBlock;

Then fire it inside the block success/failure with the appropriate value like this:

completionBlock(YES);

EDIT: By the way, please note that the return may not be on the main thread so if you plan to do a UI update you can fire the return block with a dispatch_async(dispatch_get_main_queue, ^{});

EDIT2: Since you seem to suggest this is the result of a button tap if your child is a VC waiting on the return just remember that this block will return async (obviously since that's what it is designed for) so if you need to hold the user for whatever reason you'll need to have the main thread display a loading indicator of some sort and hold user input events. Just remember that if you don't the UI will continue responding when before the completion block fires so at the very least you will want to disable the button so the user can't multi-press it and then you can reenable it when the completion block fires from the child VC.

EDIT3: Ok here is the calling code.

-(IBAction)buttonPressed
{
    [self methodInParentClassThatCallsTheAPI:param withCompletionBlock:^(BOOL success){
        if (success) {
          // do something with the UI
        } else {
            // Do something else
        }
    }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top