How do I get the RootViewController from a pushed controller?

bobobobo picture bobobobo · Nov 24, 2009 · Viewed 139.2k times · Source

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?

Answer

dulgan picture dulgan · May 2, 2013

Swift version :

var rootViewController = self.navigationController?.viewControllers.first

ObjectiveC version :

UIViewController *rootViewController = [self.navigationController.viewControllers firstObject];

Where self is an instance of a UIViewController embedded in a UINavigationController.