views:

102

answers:

2

Prior to asking this question here, I have googled aroung. In general, people suggest two ways to pass values/parameters between NavigationControllers:

  1. Via properties in the root ViewController
  2. Via Data Models

I know already that the first choice may not be the best practice. A lot of people seem to adopt this practice. However, I still don't understand how the second practice may be implemented. Does anyone happen to know any tutorial?

Moreover, is it possible to pass the value/parameter downward through constructors? I guess the only problem with that is to get back value/parameter from sub-viewcontrollers.

+1  A: 

This file defines the delegate protocol:

@protocol VCDelegate

- (void)notifyParent:(NSString*)someString;

@end

You can include it in the .h of any view controller you define. In that view controller you declare an ivar:

id<VCDelegate> delegate;

In the view controller in which you create the child view controller you include your child view controller's .h as usual. However you add

<VCDelegate>

to indicate that it implements the protocol you have defined, just as you would if you were indicating that it implemented UITableViewDelegate - you're defining a delegate that works just the same way.

When you create your child view controller:

MyChildViewController* myCVC = [[MyChildViewController alloc] initWithString:(NSString*)someString];
  myCVC.delegate = self;

So now the child view controller has a delegate which is the parent view controller, the one you are creating the child in and the one that will push it on the nav stack. You have to implement the delegate function in the parent view controller of course:

Incidentally here's where you can pass information down the stack - just set ivars after creation, same as you do the delegate ivar. You'll notice there's an initWithString that is passing a string to a custom init method, that's another way to pass information. You still do all the normal init things, just pass data additionally.

- (void)notifyParent:(NSString*)someString
{
  NSLog(@"Child view controller says %@", someString);
}

And then in the child view controller you can do

[self.delegate notifyParent:@"Hello"];

presto - parent VC gets data from child VC.

Adam Eberbach
This is great!! Than you for this great example.
Winston Chen
+1  A: 

This seems like the job for NSNotificationCenter. Have a look at this. http://stackoverflow.com/questions/3417946/sending-data-to-previous-view-in-iphone

domino