Listing methods of an Objective-C class

One of the nicer things about Objective-C is that reflection is actually pretty easy to do. This code sample lists the methods of a class:

#include <objc/runtime.h>

// List the methods of the class instance "myClass"
unsigned int methodCount;
Method* methods = class_copyMethodList([myClass class], &methodCount);
for (int i=0; i<methodCount; i++)
{
	char buffer[256];
	SEL name = method_getName(methods[i]);
	NSLog(@"Method: %@", NSStringFromSelector(name));
	char *returnType = method_copyReturnType(methods[i]);
	NSLog(@"The return type is %s", returnType);
	free(returnType);
	// self, _cmd + any others
	unsigned int numberOfArguments = method_getNumberOfArguments(methods[i]);
	for(int j=0; j<numberOfArguments; j++)
	{
		method_getArgumentType(methods[i], j, buffer, 256);
		NSLog(@"The type of argument %d is %s", j, buffer);
	}
}
free(methods);

This code originally comes from http://distriqt.com/post/863, I’ve fixed it up so you can actually compile it :) Don’t forget to replace ‘myClass’ with your class name..