Tuesday, May 12, 2009

Accessing the Root Controller from a sub view

One of the harder concepts to grasp (as someone who is new to Cocoa and the iPhone SDK) is how to navigate through the class and object hierarchy. Sometimes you feel like a rat in a maze with dead-ends every which way. In one example I wanted to do something seemingly simple: programmatically change from one tab (in a UITabView) to another, as if the user had done so themselves.

Surprisingly, this was a difficult problem to Google because the questions and answers never aligned to match my specific needs. In an unusual burst of insight, combined with some clues from Apple documentation and user posts, I came up with the following technique.

First, in the AppDelegate @interface (the main class), there is the line:

UITabBarController *rootController;

Next, in one of my subview controller interfaces, I have:

ColorMatcherAppDelegate *app;

which provides a pointer from a minor class to the main class. Next, I add the following to the @implementation of that same class:

app = [[UIApplication sharedApplication] delegate];
app.rootController.selectedIndex = 0;

When all is said and done, it only involves a few lines of code, but they sure were hard to find!

No comments:

Post a Comment