Jean Paul Scott Jean Paul Scott - 6 months ago 18
iOS Question

Popping to a specific viewcontroller in a navigation stack

I have a come across a piece of code to pop to a specific viewcontroller in a navigation stack as below

for (UIViewController* viewController in self.navigationController.viewControllers) {
if ([viewController isKindOfClass:[MyGroupViewController class]] ) {
MyGroupViewController *groupViewController = (MyGroupViewController*)viewController;
[self.navigationController popToViewController:groupViewController animated:YES];
}
}


The objective is to pop to MyGroupViewController. But I am not understanding this line of code.

MyGroupViewController *groupViewController = (MyGroupViewController*)viewController;


Whats exactly happening here. I don't think a new instance of MyGroupViewController is being created here.

Answer
//This for loop iterates through all the view controllers in navigation stack.   
for (UIViewController* viewController in self.navigationController.viewControllers) {

    //This if condition checks whether the viewController's class is MyGroupViewController 
    // if true that means its the MyGroupViewController (which has been pushed at some point)
    if ([viewController isKindOfClass:[MyGroupViewController class]] ) {

        // Here viewController is a reference of UIViewController base class of MyGroupViewController 
        // but viewController holds MyGroupViewController  object so we can type cast it here
        MyGroupViewController *groupViewController = (MyGroupViewController*)viewController;
        [self.navigationController popToViewController:groupViewController animated:YES];
    }
}

Also you can do like this

if ([viewController isKindOfClass:[MyGroupViewController class]] ) {
            [self.navigationController popToViewController:viewController  animated:YES];
        }