views:

52

answers:

2

Hi guys, can I get the list of messages that one object can response in runtime? (in Cocoa).

+5  A: 

This is not possible. Objective C supports dynamic method resolution; an object could respond to literally any message sent to it.

Wooble
For example, I once saw a class that transformed Roman numeral messages into the corresponding integers.
Chuck
Then how runtime know the object can ( or NOT) response the message? It just send the message and wait for exception?
icespace
NSObject has much built-in functionality for this: see the docs for respondsToSelector:, methodSignatureForSelector:, forwardInvocation:, doesNotRecognizeSelector:
sbooth
+4  A: 

@Wooble's answer is correct. An object can choose to respond to a message or not, and you can even add/remove/swap methods at runtime.

If you want to get a list of methods that an object currently implements (note: this is different than what messages an object will respond to), you can do so like this:

#import <objc/runtime.h>

Class class = [MyClass class];
unsigned int numMethods = 0;
Method * methods = class_copyMethodList(class, &numMethods);
for (int i = 0; i < numMethods; ++i) {
  SEL methodSelector = method_getName(methods[i]);
  NSLog(@"%@", NSStringFromSelector(methodSelector));
}
free(methods);

This is pretty neat, but be aware that this will only give you the instance methods implemented by the class. In other words, it will not give you the methods inherited from a superclass. To get those methods, you must inspect the superclass directly.

If you want to get all of the class methods implemented by a specific class, then you replace:

Class class = [MyClass class]:

with:

Class class = objc_getMetaClass(class_getName([MyClass class]));
Dave DeLong
Dear Dave: Thanks a lot, it really help, and I'd keep it in my notes.
icespace