Listing Methods at Runtime in Objective C


This post was originally published in 2012
It may contain stale & outdated information. Or it may have grown more awesome with age, like the author.

Before getting into creating my next Rapid Weaver plugin, I needed to do some experimentation to make sure what I wanted to achieve was possible. Wanting to manipulate some aspects of RWPage objects, I first required a list of methods for the RWPage class.

Thanks to Matt Gallagher’s IMP of the current method entry, I was able to generate my method list with the following code:

#import "objc/objc-class.h"
// Iterate over the class and all superclasses
Class currentClass = [RWPage class];
while (currentClass) {
    // Iterate over all instance methods for this class
    unsigned int methodCount;
    Method *methodList = class_copyMethodList(currentClass, &methodCount);
    unsigned int i = 0;
    for (; i < methodCount; i++) {
        NSLog(@"%@ - %@", [NSString stringWithCString:class_getName(currentClass) encoding:NSUTF8StringEncoding], [NSString stringWithCString:sel_getName(method_getName(methodList[i])) encoding:NSUTF8StringEncoding]);
    currentClass = class_getSuperclass(currentClass);

Method list acquired, the process of whittling it down until I found the one I wanted began.

Comments (5) | Trackback