Reputation: 11
I have a storyboard with the rootViewController class set to CoursesTableViewController.
Why in the appDelegate do I need to use a typecast as in this example...
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CoursesTableViewController *cvtc
= (CoursesTableViewController *)self.window.rootViewController;
why can't I just do this...
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CoursesTableViewController *cvtc = self.window.rootViewController;
Upvotes: 0
Views: 443
Reputation: 25917
You can actually do that. It will just warn you about that, because is expecting one thing and he is seeing another. When you are casting is just way of letting the compiler know that it's ok what you are doing.
Its type:
Upvotes: 0
Reputation: 1201
rootViewController
is a property of UIWindow
of type UIViewController
.
You need to cast it to your controller type, if you want to interface with properties and selectors specific to your type.
Upvotes: 0
Reputation: 21996
What you're doing is called downcasting. You need to do that because polymorphism allows to assign a pointer to an object of a certain class, to a pointer to an object of a subclass of it's class, but not the viceversa (because it's not said that the pointer will actually point to an object that belongs to that subclass, while instead in the opposite case this is guaranteed).
This is the UIWindow
property you're calling:
@property(nonatomic, retain) UIViewController *rootViewController;
Like you see it's of type UIViewController
,and CoursesTableViewController
is a subclass of UIViewController
.
PS: When I say it's needed I mean due to to avoid the compiler warning.
Upvotes: 2