[英]Objective C and magic methods in class
objective-c是否提供了一种拦截对不存在的类方法的调用的方法?
The forwardInvocation
method is what you are going to want to use. forwardInvocation
方法是您要使用的方法。 It is called automatically when a non-existent selector is called on an object. 在对象上调用不存在的选择器时会自动调用它。 The default behavior of this method is to call
doesNotRecognizeSelector:
(which is what outputs debug information to your console), but you can override it do anything you want. 此方法的默认行为是调用
doesNotRecognizeSelector:
这是将调试信息输出到控制台的内容),但您可以覆盖它执行任何操作。 One recommended approach by Apple is to have this method forward the method invocation to another object. Apple推荐的一种方法是让此方法将方法调用转发给另一个对象。
- (void)forwardInvocation:(NSInvocation *)anInvocation
Note that forwardInvocation
is a fairly expensive operation. 请注意,
forwardInvocation
是一个相当昂贵的操作。 An NSInvocation object needs to be created by the framework and (optionally) used to invoke a selector on another instance. NSInvocation对象需要由框架创建,并且(可选)用于在另一个实例上调用选择器。 If you are looking for a (relatively) faster method of detecting non-existent selectors then you can choose to implement
forwardingTargetForSelector
instead. 如果您正在寻找一种(相对)更快的方法来检测不存在的选择器,那么您可以选择实现
forwardingTargetForSelector
。
- (id)forwardingTargetForSelector:(SEL)aSelector
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. 你应该有Apple如何有效地覆盖这些方法的文档 ,还有一些需要注意的问题,特别是在同一个对象上覆盖
forwardInvocation
方法时会有缺少的选择器。
Yes, you can with the resolveClassMethod: class method (which is defined on NSObject): 是的,您可以使用resolveClassMethod:类方法(在NSObject上定义):
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html 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 这里还有一些值得注意的事情(第一次难倒我): http : //iphonedevelopment.blogspot.com/2008/08/dynamically-adding-class-objects.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.