Objective-C for PHP developers: Checking for a method

Jun 22, 2010   #cocoa touch  #objective-c  #php 

I created a REST-based service the other day that uses method_exists to verify that the requested action exists in the processing class. This allows my service bootstrap to be more dynamic, as I can load various classes (for example, an image processing class) and verify that the action is valid. If not, I can pass an appropriate error back to the client. Here’s a snippet of the code that I use:

$class = new $classname();
if (!method_exists($class, $methodname) {
	header(''HTTP/1.1 400 Bad Request'');
	exit(''Invalid processing action sent'');

This made me wonder how I could perform a similar check in Objective-C. There are two ways you can make this check depending on the situation.

  1. If you want to check an object instance, you would use the following:

if (![object respondsToSelector:@selector(methodname)]) {
	//Do something

  1. If you want to perform the check on the class itself, you would use:
if (![ClassName instancesRespondToSelector:@selector(methodname)]) {
	//Do something

In PHP, you perform both checks using method_exists(). If you pass an object reference as the first argument, the function verifies against the object. If you pass a class name, the function verifies against the class.

And there you go!