Alex Rivera | Logout

dismissModalViewController AND pass data back

Asked 2011-06-01T15:34:19.400
83

I have two view controllers, firstViewController and secondViewController. I am using this code to switch to my secondViewController (I am also passing a string to it):

secondViewController *second = [[secondViewController alloc] initWithNibName:nil bundle:nil];

second.myString = @"This text is passed from firstViewController!";

second.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

[self presentModalViewController:second animated:YES];

[second release];

I then use this code in secondViewController to switch back to the firstViewController:

[self dismissModalViewControllerAnimated:YES];

All of this works fine. My question is, how would I pass data to the firstViewController? I would like to pass a different string into the firstViewController from the secondViewController.

Edit
Report

1 Answer

141

You need to use delegate protocols... Here's how to do it:

Declare a protocol in your secondViewController's header file. It should look like this:

#import <UIKit/UIKit.h>

@protocol SecondDelegate <NSObject>
-(void)secondViewControllerDismissed:(NSString *)stringForFirst
@end


@interface SecondViewController : UIViewController
{
    id myDelegate;  
}

@property (nonatomic, assign) id<SecondDelegate>    myDelegate;

Don't forget to synthesize the myDelegate in your implementation (SecondViewController.m) file:

@synthesize myDelegate;

In your FirstViewController's header file subscribe to the SecondDelegate protocol by doing this:

#import "SecondViewController.h"

@interface FirstViewController:UIViewController <SecondDelegate>

Now when you instantiate SecondViewController in FirstViewController you should do the following:

// If you're using a view controller built with Interface Builder.
SecondViewController *second = [[SecondViewController alloc] initWithNibName:"SecondViewController" bundle:[NSBundle mainBundle]];
// If you're using a view controller built programmatically.
SecondViewController *second = [SecondViewController new]; // Convenience initializer that uses alloc] init]
second.myString = @"This text is passed from firstViewController!";
second.myDelegate = self;
second.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:second animated:YES];
[second release];

Lastly, in the implementation file for your first view controller (FirstViewController.m) implement the SecondDelegate's method for secondViewControllerDismissed:

- (void)secondViewControllerDismissed:(NSString *)stringForFirst
{
    NSString *thisIsTheDesiredString = stringForFirst; //And there you have it.....
}

Now when you're about to dismiss the seco

answered 2011-06-01T16:19:01.107

Your Answer