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:

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:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.