Search code examples
objective-cios5.1

Stop execution until the preceding method is done?


I have an IBAction and it looks like this.

- (IBAction) onPressed: (id) sender {

   [self openMyDelegateToSeeIfIAmReady];

   if (AmIReady == YES)
   {
      [self doMyWork];
   }
}

Right now, this doesn't work. AmIReady is a boolean and it changes to YES in openMyDelegateToSeeIfIAmReady. The thing is, before AmIReady becomes YES, this chunk of code

if (AmIReady == YES)
{
   [self doMyWork];
}

gets called and doMyWork never gets invoked. How can I make this method wait until it finishes [self openMyDelegateToSeeIfIAmReady]?

EDIT:

Here is what I have in openMyDelegateToSeeIfIAmReady

- (void) openMyDelegateToSeeIfIAmReady
{
    MyViewController *mvc = [[MyViewController alloc]initWithNibName:@"MyViewController" bundle:nil];
    mvc.delegate  = self;

    [self presentModalViewController:mvc animated:YES];
    [mvc release];
    amIReady = YES;
}

Also in this delegate (MyViewCrontroller), it requires user's input. If the user input has been entered, I need to run doMyWork.


Solution

  • If you want to have some code run after your modal view controller has been presented, use -[ UIViewController presentViewController:animated:completion:] and pass a block to the 'completion' argument.

    (This method is the replacement for presentModalViewController:animated:)

    Change your code to:

    -(IBAction)onPressed:(id)sender 
    {
        MyViewController * controller = [ [ MyViewController alloc ] initWithNibName:@"MyViewController" bundle:nil ];
        controller.delegate = self;
        [ self presentViewController:controller animated:YES completion:^{
            [ self doMyWork ] ;
        }]
    }