Pop back multiple viewcontrollers

March 20th, 2011
#ui

I sometimes find myself creating applications that have a Home viewcontroller and all other views should allow the user to directly return to this Home viewcontroller. I don't just want to push a fresh copy of the Home viewcontroller on the navigation stack. Instead, I need to loop through the navigation stack until I find the existing Home viewcontroller and pop back directly to it.

- (void)homeButtonPressed:(id)sender{
    NSArray *navArray = [self.navigationController viewControllers];
    
    for (int x = 0; x < [navArray count]; x++) {
        
        UIViewController *viewController = [navArray objectAtIndex:x];
        
        if ([viewController isKindOfClass:[HomeViewController class]]) { //change HomeViewController to your intended target
            [self.navigationController popToViewController:viewController animated:YES];
        }
    }
}

What do you think? Let me know by getting in touch on Twitter - @wibosco