我有一个对象,我想列出它响应的所有选择器。感觉这应该是完全有可能的,但我在寻找API时遇到了麻烦。
发布于 2008-12-01 05:54:53
这是一个基于运行时C函数的解决方案:
给定一个可从对象获取的类对象,class_copyMethodList返回一个类方法列表。
#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 */
发布于 2013-11-06 16:43:38
我认为通常你会想在控制台中做这件事,而不是用调试代码把你的代码搞得一团糟。这就是你在lldb中调试的方法:
(假设对象为t)
p int $num = 0;
expr Method *$m = (Method *)class_copyMethodList((Class)object_getClass(t), &$num);
expr for(int i=0;i<$num;i++) { (void)NSLog(@"%s",(char *)sel_getName((SEL)method_getName($m[i]))); }
发布于 2016-02-10 10:09:33
使用Swift也可以做到这一点:
let obj = NSObject()
var mc: UInt32 = 0
let mcPointer = withUnsafeMutablePointer(&mc, { $0 })
let mlist = class_copyMethodList(object_getClass(obj), mcPointer)
print("\(mc) methods")
for i in 0...Int(mc) {
print(String(format: "Method #%d: %s", arguments: [i, sel_getName(method_getName(mlist[i]))]))
}
输出:
251 methods
Method #0: hashValue
Method #1: postNotificationWithDescription:
Method #2: okToNotifyFromThisThread
Method #3: fromNotifySafeThreadPerformSelector:withObject:
Method #4: allowSafePerformSelector
Method #5: disallowSafePerformSelector
...
Method #247: isProxy
Method #248: isMemberOfClass:
Method #249: superclass
Method #250: isFault
Method #251: <null selector>
使用运行iOS 9.2,Xcode7.2版(7C68)的6s模拟器进行测试。
https://stackoverflow.com/questions/330030
复制相似问题