How to test which class presented a UIViewController

The NSObject class has an interesting method called isKindOfClass. As the name suggests it lets you test what kind of class it belongs to. As everything we use inherits from NSObject, this method is available in our own classes we use in iOS and Mac development.

This method can come in handy for example when three different classes present the same view controller and you’d like to make decisions based on which controller has presented your content. Consider the following two example.

If you present a UIViewController via a modal segue you can test which class the presenting view controller belonged to like so:

// grab a reference to the presenting view controller 
id thePresenter = self.presentingViewController;

// and test its class
if ([thePresenter isKindOfClass:[YourViewController class]]) {
    // do this
} else {
    // do that
}

If however your view controller was presented via a UINavigationController then the above isn’t going to work. Instead you need to check which view controller was on the navigation stack previously.

Here’s how to do this:

// grab a reference to the previous view controller 
id thePresenter = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];

// and test its class
if ([thePresenter isKindOfClass:[YourViewController class]]) {
    // do this
} else {
    // do that
}




Leave a Reply