Try the search, it's linked to some great forums

Monday, June 11, 2012

Delegation - passing info between controllers

The flipside template in Xcode provides probably the simplest implementation of a custom delegate that there is.  It allows the programmer to pass data from the flipside (settings data, flagHeight) to the MainView.  Here it is;

Create the delegate protocol and it's methods, define the delegate property and define a property to pass (flipsideInfo);
in FlipsideViewController.h -
@class FlipsideViewController;    // forward reference

@protocol FlipsideViewControllerDelegate   // delegate name & required method
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
@end

@interface FlipsideViewController : UIViewController

@property (weak, nonatomic) id delegate;
@property (strong, nonatomic) IBOutlet UITextField *flipsideInfo;  // data to pass on

Oh, and don't forget to synthesize the delegate;
in FlipsideViewController.m - 
@implementation FlipsideViewController
@synthesize delegate = _delegate;

Set the MainViewController to conform the the delegate, FlipsideViewControllerDelegate;
in MainViewController.h -
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

Implement the required delegate method flipsideViewControllerDidFinish: 
in MainViewController.m -
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    self.myAssistantLabel.text = controller.flipsideInfo.text;  // flipsideInfo is a property of the flipsideVC
    [self dismissModalViewControllerAnimated:YES];
}

And that's all she wrote!