views:

615

answers:

2

I have an object, and I want to list all the selectors to which it responds. It feels like this should be perfectly possible, but I'm having trouble finding the APIs.

+1  A: 

Something like this should work (just put it in the object you're curious about). For example if you have an object that's a delegate and want to know what 'hooks' are available this will print out messages to give you that clue:

-(BOOL) respondsToSelector:(SEL)aSelector { printf("Selector: %s\n", [NSStringFromSelector(aSelector) UTF8String]); return [super respondsToSelector:aSelector]; }

Note that I discovered this in the iPhone Developer's Cookbook so I can't take credit! For example output I get from a UIViewController that implements the protocols :

Selector: tableView:numberOfRowsInSection:

Selector: tableView:cellForRowAtIndexPath:

Selector: numberOfSectionsInTableView:

Selector: tableView:titleForHeaderInSection:

Selector: tableView:titleForFooterInSection:

Selector: tableView:commitEditingStyle:forRowAtIndexPath:

Selector: sectionIndexTitlesForTableView:

Selector: tableView:sectionForSectionIndexTitle:atIndex: ... ... etc.,etc.

Rob
+8  A: 

This is a solution based on the runtime C functions:

class_copyMethodList returns a list of class methods given a Class object obtainable from an object.

#import <objc/runtime.h>

[..]

SomeClass * t = [[SomeClass alloc] init];

int i=0;
unsigned int mc = 0;
Method * mlist = class_copyMethodList(object_getClass(t), &mc);
NSLog(@"%d methods", mc);
for(i=0;i<mc;i++)
    NSLog(@"Method no #%d: %s", i, sel_getName(method_getName(mlist[i])));

/* note mlist needs to be freed */
diciu