Objective C 和类中的魔法方法 [英] Objective C and magic methods in class

查看:54
本文介绍了Objective C 和类中的魔法方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

objective-c 是否提供了一种方法来拦截对不存在的类方法的调用?

Does objective-c offer a way to intercept calls to class method that does not exist?

推荐答案

forwardInvocation 方法就是您要使用的方法.当在对象上调用不存在的选择器时,它会自动调用.此方法的默认行为是调用 doesNotRecognizeSelector:(这是将调试信息输出到您的控制台),但您可以覆盖它做任何您想做的事情.Apple 推荐的一种方法是让此方法将方法调用转发到另一个对象.

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 call doesNotRecognizeSelector:(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.

- (void)forwardInvocation:(NSInvocation *)anInvocation

请注意,forwardInvocation 是一个相当昂贵的操作.NSInvocation 对象需要由框架创建,并且(可选)用于调用另一个实例上的选择器.如果您正在寻找一种(相对)更快的方法来检测不存在的选择器,那么您可以选择实现 forwardingTargetForSelector.

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 implement forwardingTargetForSelector instead.

- (id)forwardingTargetForSelector:(SEL)aSelector

你应该 Apple 的关于如何有效地覆盖这些方法的文档,有一些问题需要注意,特别是在覆盖具有缺失选择器的同一对象上的 forwardInvocation 方法时.

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.

这篇关于Objective C 和类中的魔法方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆