列出Objective-C对象的选择器

Air*_*Ltd 35 objective-c selector

我有一个对象,我想列​​出它响应的所有选择器.感觉这应该是完全可能的,但我找不到API.

dic*_*ciu 73

这是一个基于运行时C函数的解决方案:

class_copyMethodList返回给定可从对象获取的Class对象的类方法列表.

#import <objc/runtime.h>
Run Code Online (Sandbox Code Playgroud)

[..]

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 */
Run Code Online (Sandbox Code Playgroud)

  • 这个答案为您提供了类方法.如果你想让对象响应的方法替换这行`Method*mlist = class_copyMethodList(object_getClass(t),&mc);``这个`Method*mlist = class_copyMethodList(t,&mc);` (8认同)
  • @bugloaf至少在iOS 9上,如果传递常规对象,它将出现段错误。 (2认同)

jos*_*new 26

我想通常你会想在控制台中这样做,而不是用调试代码混乱代码.这是在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]))); }
Run Code Online (Sandbox Code Playgroud)


JAL*_*JAL 6

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]))]))
}
Run Code Online (Sandbox Code Playgroud)

输出:

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>
Run Code Online (Sandbox Code Playgroud)

使用运行iOS 9.2,Xcode版本7.2(7C68)的6s模拟器进行测试.