Search code examples
iosobjective-cios5modelcallback

Creating a callback once a model has completed a task


The workflow in question here is as follows:

User clicks to create a game, a Game Model is called in which the game is created.

-- What needs to happen here is some form of callback to the View Controller to confirm the game was created so that a new VC can be pushed to the screen? What is the best way to accomplish this.

A prompt is shown to the user to decide to create the game as follows:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"button %i",buttonIndex);
    if (buttonIndex == 0) {
        // Cancel button pressed we will clear the gameNewOpponentUser to be clean
        self.gameNewOpponentuser = nil;
    } else {
        // Start Game button pressed
        [MESGameModel createNewGameWithUser:[PFUser currentUser] against:self.gameNewOpponentuser];
    }
}

The game model then creates a game with Parse as follows:

        PFObject *newGame = [PFObject objectWithClassName:@"Game"];
        [newGame setObject:[PFUser currentUser] forKey:kMESGameUser1];
        [newGame setObject:user2 forKey:kMESGameUser2];
        [newGame saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {

            }
        }];

As you can see I have a succeeded that I can use to confirm it was created correctly. However, how do I feed that is created back to the VC from the model.


Solution

  • Use a completion block.

    In your model add a completion handler to your game-creating method something like so:

    -(void) startNewGameWithCompletionHandler: (void(^)()) handler {
        PFObject *newGame = [PFObject objectWithClassName:@"Game"];
        [newGame setObject:[PFUser currentUser] forKey:kMESGameUser1];
        [newGame setObject:user2 forKey:kMESGameUser2];
        [newGame saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                if (handler) handler(); //execute the code-block provided by the caller
            }
        }];
    }
    

    In your viewController:

    [modelObject startNewGameWithCompletionHandler: ^{
      //push some vc here or whatever....
    }];
    

    Of course you could also define some parameters for the block (eg pass the success variable or anything else you might need) or you might want to put in some error checking / handling.