ProgrammerGuide.Net | Step by Step Programmer Guide

Checking if a Method or Property Exists in an Object using Objective-C | iOS Programmer Guide

There is a simple way of testing if a method exist in an object using Objective-C. This can be achieved using the respondsToSelector method. The code snippet is given below

if ([obj respondsToSelector:@selector(methodName:withParam:)]) {
   [obj methodName:123 withParam:456];
}

Here, the method that we were checking if exists using objective-C is “methodName” that has two parameters.

We can also use the static message instancesRespondToSelector:(SEL)selector if you would like to call one constructor or another one depending on this. This method allows you to check before having the instance of the class. The objective-c code snippet is given below:

[MyClass instancesRespondToSelector:@selector(someMethod:withParams:)]
or like this:
[[myObject class] instancesRespondToSelector:@selector(someMethod:withParams:)]

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?