views:

566

answers:

1

So, I push a view controller from RootViewController like:

[self.navigationController pushViewController:anotherViewController animated:YES] ;

BUT, FROM anotherViewController now, I want to access the RootViewController again.

I'm trying

// (inside anotherViewController now)
///RootViewController *root = (RootViewController*)self.parentViewController ; // No.
// err
RootViewController *root = (RootViewController*)[self.navigationController.viewControllers objectAtIndex:0] ; // YES!! it works

I'm not sure WHY this works and I'm not sure if its the best way to do it. Can somebody comment on a better way to get the RootViewController from a controller you've pushed into that RootViewController's navigationController and whether or not the way I've done it is reliable or not?

+1  A: 

Use the viewControllers property of the UINavigationController.

// Inside anotherViewController
NSArray *viewControllers = self.navigationController.viewControllers
UIViewController rootViewController = [viewControllers objectAtIndex:viewControllers.count - 2];

This is the standard way of getting the "back" view controller. The reason objectAtIndex:0 works is because the view controller you're trying to access is also the root one, if you were deeper in the navigation, the back view would not be the same as the root view.

Ben S
:) ty. It still seems hacky - :) I really wanted an "official" member to do the job, something like self.navigationController.rootViewController, but alas, no such thing..
bobobobo