iosobjective-cxcodeuitabbarcontrollerpoptoviewcontroller

call popToRootViewController from another tab


I have tab bar with navigation controller app using storyboard ,
my purpose is to press a button in tab3 and in the background I want tab1 to "popToRootViewController"

the button in tab3 viewcontroller:

- (IBAction)Action:(id)sender {

    vc1 * first = [[vc1 alloc]init];
    [first performSelector:@selector(popToRootViewController) withObject:Nil];

}

the code in the tab1 viewcontroller

-(void)popToRootViewController{

    [self.navigationController popToRootViewControllerAnimated:NO];
    NSLog(@"popToRootViewController");
}

I get the popToRootViewController in logs, but the action didn't perform.

that solve the problem:

- (IBAction)Action:(id)sender {

        [[self.tabBarController.viewControllers objectAtIndex:0]popToRootViewControllerAnimated:NO];


    }

Solution

  • The way you are doing it:

    vc1 * first = [[vc1 alloc]init];
    [first performSelector:@selector(popToRootViewController) withObject:Nil];
    

    is not correct. Indeed, you are creating a whole new controller here, completely independent from your existing controllers and not belonging to any navigation controller. For this reason, self.navigationController is nil in popToRootViewController.

    You might try doing something like:

     //-- this will give you the left-most controller in your tab bar controller
     vc1 * first = [self.tabBarController.viewControllers objectAtIndex:0];
    [first performSelector:@selector(popToRootViewController) withObject:Nil];