Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data across child navigation controllers

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.

enter image description here

According to Apple's documentation, UINavigationController shouldn't be subclassed, so I can't create a delegate and pass data.

Question:

  • how can I pass data from AAA to CCC ?
  • any work arounds to achieve this ?
like image 306
user1046037 Avatar asked Mar 23 '12 00:03

user1046037


People also ask

How do I pass data from one ViewController to another in swift?

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.

How do I move an object from one ViewController to another?

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.”


2 Answers

If you have a pointer to the navigation controller, you can get its viewControllers array. In that array, objectAtIndex:0 will be CCC.

like image 59
jsd Avatar answered Sep 20 '22 17:09

jsd


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
like image 4
JWK Avatar answered Sep 20 '22 17:09

JWK