获取 Objective-C 类或实例的所有方法
在 Objective-C 中,我可以测试给定的类或实例是否响应某些选择器。但是如何查询一个类或实例的所有方法或类的属性(例如所有方法或属性的列表)?
In Objective-C I can test whether a given class or instance responds to certain selectors. But how can query a class or instance for all its methods or properties of a class (e.g. a list of all methods or properties)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除了 Buzzy 的答案之外,出于调试目的,您还可以使用
-[NSObject _methodDescription]
私有方法。在 lldb:
或 code: 中,
输出将如下所示:
In addition to Buzzy's answer, for debugging purposes you may use the
-[NSObject _methodDescription]
private method.Either in lldb:
or in code:
Output will look as following:
您可以执行此操作,并且在 https://developer.apple .com/library/mac/documentation/cocoa/Reference/ObjCRuntimeRef/index.html
要获取类的所有实例或类方法,您可以使用
class_copyMethodList
并迭代结果。示例:您需要对此方法进行两次单独的调用。一个用于实例方法,另一个用于类方法:
在元类上调用相同的方法将为您提供所有类方法
You can do this and it is extremely well documented at https://developer.apple.com/library/mac/documentation/cocoa/Reference/ObjCRuntimeRef/index.html
To fetch all the instance or class methods of a class, you may use
class_copyMethodList
and iterate over the results. An example:You will need to make two separate calls to this method. One for the instance methods and another for the class methods:
Calling the same on the metaclass will give you all the class methods
您需要使用 Objective C 运行时方法,请参见此处: https://developer.apple .com/reference/objectivec/objective_c_runtime
You'll want to use the Objective C runtime methods, see here: https://developer.apple.com/reference/objectivec/objective_c_runtime
这可以通过 objc_method_list 实现。为了枚举您的方法,您必须事先注册所有方法。
该过程很简单:声明函数后,您可以创建 objc_method 的实例并注册函数名称。然后将 objc_method 添加到 objc_method_list 中,最后将 objc_method_list 传递给 class_addMethods 。
以下是帮助您入门的链接:
http://theocacao.com/document.page/327
This is possible via objc_method_list. In order to enumerate your methods, you will have to register all your methods before hand.
The process is straight forward: after you've declared your function you can create an instance of objc_method and register the function name. Then add the objc_method to a objc_method_list and finally pass the objc_method_list to class_addMethods..
Here is a link to get you started:
http://theocacao.com/document.page/327