1
votes
1. UINavigationController *rnc = self.app.window.rootViewController;

I get warning Incompatible pointer types initializing UINavigationController with an expression of type UIViewController

2. UINavigationController *rnc = (UINavigationController *)self.app.window.rootViewController;

The option 1 shows warning "Incompatible pointer types initializing UINavigationController with an expression of type UIViewController" and the option 2 not. Why ? What is a risk if I will not cast like in the option 2 ?

UPDATED

What is a risk of casting UIViewController to UINavigationController ?

1
@adobels The risk is that rootViewController on window is not actually an instance of UINavigationController* (or subclass) and your app crashes at runtime. Swift mitigates this issue by requiring casts in a form of rnc = window.rootViewController as! UINavigationController. The "cast" (it isn't really cast) will be checked at runtime. - bbum

1 Answers

3
votes

The warning is pretty clear. In case 1 , the rootViewController is of type UIViewController and you are giving the UIViewController instance to the UINavigationController.

In case 2, you are making a cast to convert the UIViewController to UINavigationController,hence the compiler didn't gave any warning.

You should not try to convert UIViewController to a UINavigationController. They both are different. UINavigationController is a subclass of UIViewController.

If you want to make your rootViewController embedded in a navigation controller, then you should do something like:

 YourRootViewController *rootViewController = self.app.window.rootViewController;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:rootViewController];