Re-assigning RootViewController after successful login
cocoa-touch, ios, objective-c
Solution
The documentation of the `rootViewController` property states:
If the window has an existing view hierarchy, the old views are removed before the new ones are installed.
So if you don't keep your own reference to the `LoginViewController`, it will be destroyed.
Perhaps this: RootViewController Switch Transition Animation is also interesting for you, as it describes how to switch the root view controller with an animation.
Problem
My iOS app opens with a login prompt. Once the user logs in, it switches to the main view. In application:didFinishLaunchingWithOptions, I set the RootViewController to a LoginViewController. The LoginViewController has the AppDelegate as its delegate: ``` LoginViewController *login = [[LoginViewController alloc] init]; [login setDelegate:self]; [[self window] setRootViewController:login]; ``` If the login is successful, the LoginViewController calls the AppDelegate's userDidLogin method: ``` if([[self delegate] respondsToSelector:@selector(userDidLogin)]) { [[self delegate] userDidLogin]; } ``` userDidLogin creates a new UINavigationController and assigns it as the RootViewController: ``` - (void)userDidLogin { MainRecordViewController *mainRecordViewController = [[MainRecordViewController alloc] init]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mainRecordViewController]; [[self window] setRootViewController:navController]; } ``` By adding an NSLog to the LoginViewController's dealloc method, it appears that the LoginViewController is destroyed at that stage and that execution continues as expected. I haven't done anything to explicitly close the LoginViewController, just relied on the assumption that assigning a new RootViewController will mean that the old one disappears and is tidied away by ARC. Can I rely on that always being the case? Is this a sensible approach? Thanks in advance. James