开发者

How to know all messages that one object can response?

can I get the list of messages that o开发者_如何学Gone object can response in runtime? (in Cocoa).


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


@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]));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜