objective-c中类似于method_missing的功能(即运行时的动态委派) [英] method_missing-like functionality in objective-c (i.e. dynamic delegation at run time)

查看:98
本文介绍了objective-c中类似于method_missing的功能(即运行时的动态委派)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个方法调用动态转换(在运行时)。

I'm trying to transform one method call into another dynamically (at runtime).

例如,我想要如下:

[obj foo]

委托给:

[obj getAttribute: @"foo"]

'我喜欢做这个动态,因为我不提前知道这些方法的名称或属性将是什么)。

(I'd like to do this dynamically as I don't know ahead of time what those method names or attributes are going to be).

我看到有一个钩子:

 - (id) forwardingTargetForSelector: (SEL) aSelector

尽管如此,我只想保持对象为self,并转换方法参数。

That only seems to work for delegation, though, I want to keep the object as "self" and transform the method arguments.

我应该在哪里寻找这种行为?您可以使用方法 -forwardInvocation:

Where should I look for this sort of behavior? Is it even possible in obj-c?

推荐答案

code>为此。它需要一个完整的 NSInvocation 对象,表示方法调用,您可以处理它,但是您希望。如果这样做,您还应该覆盖 -methodSignatureForSelector:以返回正确的 NSMethodSignature -forwardInvocation:在未知选择器上工作)。还建议您覆盖 -respondsToSelector:以声明您可以处理相关的选择器。

You can use the method -forwardInvocation: for that. It takes a full NSInvocation object which represents the method call, and you can handle it however you wish. If you do this, you should also override -methodSignatureForSelector: to return the correct NSMethodSignature (required for -forwardInvocation: to work on unknown selectors). It's also recommended that you override -respondsToSelector: to declare that you can handle the selector in question.

这篇关于objective-c中类似于method_missing的功能(即运行时的动态委派)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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