Overview
I have an iOS project which contains 2 navigation controllers as shown in the pic attached below.
I would like to pass some data when it segues from AAA to CCC but there is a navigation controller between AAA and CCC.
According to Apple's documentation, UINavigationController shouldn't be subclassed, so I can't create a delegate and pass data.
Question:
If you have a value in one view controller and want to pass it to another, there are two approaches: for passing data forward you should communicate using properties, and for passing data backwards you can either use a delegate or a block.
Control + click the UI element you are going to use to make the bridge and drag to the second View Controller. Select the “Show” option from the “Action Segue” menu. Control + click the button and drag to the second ViewController, then select “Show.”
If you have a pointer to the navigation controller, you can get its viewControllers array. In that array, objectAtIndex:0 will be CCC.
For anyone who is unclear on how to implement the accepted answer, here is a code example to more clearly explain how to "have a pointer to the navigation controller." The following code passes an NSString from AAA (AAAViewController) to CCC (CCCViewController) with an identifier named "ToCCC" for the segue.
1) Create a pointer to foo
in CCCViewController.h
.
// CCCViewController.h
#import <UIKit/UIKit.h>
@interface CCCViewController : UITableViewController
@property (strong, nonatomic) NSString *foo;
@end
2) In AAAViewController.m
, create a pointer to CCCViewController (via the navigation controller) and then set foo
.
// AAAViewController.m
#import "AAAViewController.h"
#import "CCCViewController.h" // Note the import statement for CCC.
@implementation AAAViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString: @"ToCCC"])
{
CCCViewController *ccc = [[segue.destinationViewController viewControllers] objectAtIndex: 0];
ccc.foo = @"A string passed from AAA";
}
}
@end
3) Do something with foo
in CCCViewController.m
(e.g. log it to the console).
// CCCViewController.m
#import "CCCViewController.h"
@implementation CCCViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Log foo to the console.
NSLog(@"%@", _foo);
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With