views:

51

answers:

1

What is the best way for a view added via presentModalViewController to communicate its dismissal with the class which invoked the call?

In one of my methods, I use presentModalViewController:animated: to popup a scoreboard where a player enters their name, then clicks OK. Everything is working fine with the scoreboard, but when I use dissmissModaleViewController I'd like a way for the class which called presentModeViewController to display an alert.

I tried to but the following in the method which called the presentModalViewController:

[self presentModalViewController:"myNib" animated:YES];
[alert show];

But the alert code runs after the presentModalViewController runs, so I assume that when presentModalViewController is called, it doesn't stop the code executing outside of it.

Anyway, I need the alert options to be handled within the class which calls the presentModalViewController, so what is the best way to go about it?

+3  A: 

In my opinion the best to do this is by implementing a protocol and suscribe your caller class as delegate of the scoreView, try implementing this in your scoreView header file:

@portocol ScoreViewDelegate <NSObject> 

- (void)userDidEnterData:(NSString *)data;

@end

@interface ScoreView:.... {
      // Any instance variable ...

      id <ScoreViewDelegate> delegate;  // delegate shouldn't be pointer
}

@property (assign) id <ScoreViewDelegate> delegate;

...
@end

Inside your ScoreView class implementation you should have any method that handles the user interactions so when they are done with inserting data the method must send the message to it's delegate:

@implementation ScoreView
@synthesize delegate;         // Don't forget to synthesize your delegate

- (IBAction)userIsDone:(id)sender {
       // Do some stuff

      [delegate userDidEnterData:self.aTextField.text];
}

...

@end

Now, this code should send the message to the caller class but it shoul be suscribed as delegate so you must do it like this:

@interface CallerClass:NSObject <SocreViewDelegate> {
...

@end

@implemetation CallerClass
...

     ScoreView *sView = ....;
     sView.delegate = self;

//Because it's now suscribed as delegate, it should implement the method
- (void)userDidEnterData:(NSString *)data {
       // Here you have the data
       // Present alert
}

I hope you found this useful to your case.

iPhoneDevProf
+1, very detailed. This is what Apple also does on MKComposeMailViewController et. al.
Johannes Rudolph