Snowman
Snowman

Reputation: 32061

Accessing a UIWindow's rootViewController?

Here is the applicationDidFinishLaunching method for the ECSlidingViewController demo code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ECSlidingViewController *slidingViewController = (ECSlidingViewController *)self.window.rootViewController;
  UIStoryboard *storyboard;

  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
  } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];
  }

  slidingViewController.topViewController = [storyboard instantiateViewControllerWithIdentifier:@"FirstTop"];

  return YES;
}

What doesn't make sense to me is the first line:

ECSlidingViewController *slidingViewController = (ECSlidingViewController*)self.window.rootViewController;

I just don't get how you can grab the window's root view controller, and cast it like that as you please? What exactly does that line do and how does it work?

Upvotes: 1

Views: 1257

Answers (1)

jonkroll
jonkroll

Reputation: 15722

In your storyboard you have a scene set up for your root view controller (i.e. the rootViewController checkbox is checked in the properties, and the initial arrow on the canvas is pointing at this view controller). The class for that view controller is set in the properties inspector. In your case the class is set to ECSlidingViewController. This determines the class of the object that storyboard will instantiate.

UIWindow has a property rootViewController that returns that object. The type of the property on UIWindow is UIViewController - so the window knows it is a view controller, but it doesn't know any more specifics than that. Your ECSlidingViewController class is a subclass of UIViewController. When it is returned your code is casting it as a more specific object so that you can work with it as the more specific object that it actually is.

Upvotes: 4

Related Questions