I have a long View Controllers hierarchy;
in the first View Controller I use this code:
SecondViewController *svc = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self presentModalViewController:svc animated:YES];
[svc release];
In the second View Controller I use this code:
ThirdViewController *tvc = [[ThirdViewController alloc] initWithNibName:@"ThirdViewController" bundle:nil];
[self presentModalViewController:tvc animated:YES];
[tvc release];
and so on.
So there is a moment when I have many View Controllers and I need to come back to the first View Controller. If I come back one step at once, I use in every View Controller this code:
[self dismissModalViewControllerAnimated:YES];
If I want to go back directly from the, say, sixth View Controller to the first one, what I have to do to dismiss all the Controllers at once?
Thanks
Yes. there are already a bunch of answers, but I'm just going to add one to the end of the list anyway. The problem is that we need to get a reference to the view controller at the base of the hierarchy. As in @Juan Munhoes Junior's answer, you can walk the hierarchy, but there may be different routes the user could take, so that's a pretty fragile answer. It is not hard to extend this simple solution, though to simply walk the hierarchy looking for the bottom of the stack. Calling dismiss on the bottom one will get all the others, too.
-(void)dismissModalStack {
UIViewController *vc = self.presentingViewController;
while (vc.presentingViewController) {
vc = vc.presentingViewController;
}
[vc dismissViewControllerAnimated:YES completion:NULL];
}
This is simple and flexible: if you want to look for a particular kind of view controller in the stack, you could add logic based on [vc isKindOfClass:[DesiredViewControllerClass class]]
.