Proper way to call popToViewController - iOS

2019-09-09 21:35发布

I am having an argument with my team member regarding popToViewController.

For me best approach is Can i pop to Specific ViewController?

But he think we should create a static instance of the viewController and then call

-(void)takeToPreviousViewController {
    if([IVPreviousViewController sharedInstance]) {
        [self.navigationController popToViewController:[IVPreviousViewController sharedInstance] animated:YES];
    }
}

I strongly appose this approach because we're creating a public method in IVPreviousViewController which has no relation to the currentViewController. We should always avoid method expose like this.

Can anyone point me a solid reason about the best approach.

Update:

IVPreviousViewController.h

__weak static IVPreviousViewController * staticEventDetailViewController;

    +(IVPreviousViewController *)sharedInstance;

IVPreviousViewController.m

+(IVPreviousViewController *)sharedInstance {
    return staticEventDetailViewController;
}

Reason of this approach - On a particular use case in our viewController it has to popbackto IVPreviousViewController

2条回答
老娘就宠你
2楼-- · 2019-09-09 21:54

This is my take on this:

I support your opinion. We should avoid static shared instances where ever possible. Static instances remains in memory until app life time. All the other objects being referenced from this instance also then remain in memory.

With the approach mentioned in above shared link VC that is no more needed will be taken out of memory. Also, if you do not have many VCs, better have a weak reference to target VC from source VC instead of looping and selecting the target VC.

And yes, in context of objective C for better readability, header file should contain only those APIs that are really needed by outside world.

查看更多
姐就是有狂的资本
3楼-- · 2019-09-09 21:58

I think you can do something like this

-(void)popToVC:(ClassNameOfTheViewController)controllerClass{
 for(UIViewController *vc in self.navigationController.viewControllers)
    if( [vc isKindOfClass:[controllerClass class]]){
     [self.navigationController popToViewController:vc animated:YES];
   }
}
查看更多
登录 后发表回答