简体   繁体   中英

iOS: Correct way to dispose of view controllers and go back to main screen

I have a login screen, a second screen and a third screen. I want to have a button in the third screen to go back to the login screen and delete the current instances of second and third screen.

What I have is a push segue from login to second screen and a push segue from second to third screen. I've put a bar button item on the navigation bar of the third screen and attached a modal segue to it to go back to the login screen. On clicking I get a new login screen thats empty, this is just creating a new instance of it right? How do I delete the previous instances so that memory is saved? In Android we pass a flag FLAG_ACTIVITY_CLEAR_TOP to the intent that clears the other activities. Is there something analogous to this in iOS?

Instead of creating new object on third screen just use the following code inside navigation bar button action method. Ur remaining objects will be destroyed automatically.

[self.navigationController popToRootViewControllerAnimated:YES];

If you want to create a new instance of the Login View Controller and dispose all other controllers, your code should be like this.

   LoginViewController *loginController=[[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"loginController"]; 
   UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:loginController];
   [[(AppDelegate*)[UIApplication sharedApplication].delegate window] setRootViewController:navController];

PS: If you do not mind keeping the same instance of LoginViewController you had before, then user2894531's answer is correct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM