23

I want to be able to check the type of a UIViewController to see if it is of a certain type like this

c code

if (typeof(instance1) == customUIViewController) 
{
  customUIViewController test = (customViewController)instance1;

  // do more stuff
}
Pål Brattberg
  • 4,568
  • 29
  • 40
Arcadian
  • 4,312
  • 12
  • 64
  • 107

6 Answers6

44

The isKindOfClass: method indicates whether an object is an instance of given class or an instance of a subclass of that class.

if ([instance1 isKindOfClass:[CustomUIViewController class]]) {
    // code
}

If you want to check whether an object is an instance of a given class (but not an instance of a subclass of that class), use isMemberOfClass: instead.

James Huddleston
  • 8,410
  • 5
  • 34
  • 39
18
var someVC: UIViewController

if someVC is MyCustomVC {
    //code
}
Harry Ng
  • 1,070
  • 8
  • 20
9

Swift version:

var someVC: UIViewController

if someVC.isKindOfClass(MyCustomVC) {
    //code
}
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
5

Try:

[vc isKindOfClass:[CustomViewController class]];
Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
5

I just wanted to add in addition to this answer that if you're wanting to see if a view controller is of a certain type in a switch statement (in Swift) you can do it like this:

var someVC: UIViewController?

switch someVC {
    case is ViewController01: break
    case is ViewController02: break
    case is ViewController03: break
    default: break
}
Community
  • 1
  • 1
John R Perry
  • 3,916
  • 2
  • 38
  • 62
3

Swift 3.0 in latest, we have to add a self along with the class name or it will throw an error "Expected member name or constructor call after type name" the below code u can use for Swift 3 and above

  for viewController in viewControllers {
                            if viewController.isKind(of: OurViewController.self){
                                print("yes it is OurViewController")
                                self.navigationController?.popToViewController(viewController, animated: true)
                            }
                        }
SARATH SASI
  • 1,395
  • 1
  • 15
  • 39