Objective C 和课堂上的魔法方法
Objective-C 是否提供了一种方法来拦截对不存在的类方法的调用?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
Objective-C 是否提供了一种方法来拦截对不存在的类方法的调用?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
您将要使用
forwardInitation
方法。当对对象调用不存在的选择器时,会自动调用它。此方法的默认行为是调用 doesNotRecognizeSelector:(它将调试信息输出到控制台),但您可以覆盖它以执行任何您想要的操作。 Apple 推荐的一种方法是让此方法将方法调用转发到另一个对象。请注意,
forwardInitation
是一个相当昂贵的操作。 NSIncation 对象需要由框架创建并(可选)用于调用另一个实例上的选择器。如果您正在寻找一种(相对)更快的方法来检测不存在的选择器,那么您可以选择实现forwardingTargetForSelector
。您应该Apple 文档 对于如何有效地重写这些方法,有一些问题需要注意,特别是在缺少选择器的同一对象上重写
forwardInvocau
方法时。The
forwardInvocation
method is what you are going to want to use. It is called automatically when a non-existent selector is called on an object. The default behavior of this method is to calldoesNotRecognizeSelector:
(which is what outputs debug information to your console), but you can override it do anything you want. One recommended approach by Apple is to have this method forward the method invocation to another object.Note that
forwardInvocation
is a fairly expensive operation. An NSInvocation object needs to be created by the framework and (optionally) used to invoke a selector on another instance. If you are looking for a (relatively) faster method of detecting non-existent selectors then you can choose to implementforwardingTargetForSelector
instead.You should Apple's documentation for how to override these methods effectively, there are some gotcha's to watch out for, particularly when overriding the
forwardInvocation
method on the same object that will have the missing selectors.是的,您可以使用resolveClassMethod:类方法(在NSObject上定义):
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html
这里还有一些需要注意的地方(第一次难住了我):http://iphonedevelopment.blogspot.com/2008/08/dynamically-adding-class-objects.html
Yes, you can with the resolveClassMethod: class method (which is defined on NSObject):
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html
Here is also something to watch out for (stumped me the first time): http://iphonedevelopment.blogspot.com/2008/08/dynamically-adding-class-objects.html