How can a method tell which view controller called

2020-07-10 09:50发布

问题:

I want to get the current view controller in my own method. I mean i have two view controllers which are calling a same method. In that i want to diffentiate from which view controller class is calling that method.

Please help me out

回答1:

Lets say myCommonMethod: is the common function called from both the view controller , you could check your viewController whether it's the member of a class or not using isMemberOfClass: method of NSObject.

-(void) myCommonMethod:(UIViewController*) aViewController
{
      if([aViewController isMemberOfClass:NSClassFromString(@"MyFirstController")])
      {
      }
      else if([aViewController isMemberOfClass:NSClassFromString(@"MySecondController")])
      {  

      }
}


回答2:

If it is a navigation based app, you can get the current view controller by,

UIViewController *currentVC = self.navigationController.visibleViewController;


回答3:

If both of your view controllers are calling same function then you can pass self as a parameter in that method for this you can write function as -

-(void) functionName:(UIViewController*) viewController