What's the best practice to pass value/parameter between NavigationControllers?
Prior to asking this question here, I have googled aroung. In general, people suggest two ways to pass values/parameters 开发者_C百科between NavigationControllers:
- Via properties in the root ViewController
- 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.
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.
This seems like the job for NSNotificationCenter
. Have a look at this.
sending data to previous view in iphone
精彩评论