如何调用祖父母方法 [英] How to call a grandparent method

查看:55
本文介绍了如何调用祖父母方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用我班上的祖父母方法.

i need to call a grandparent method of my class.

@class Grandparent
+--->@class Parent   
     +---->@class Child

每个类都实现一个方法:

Every class implement a method:

-(void)foo

如果我想从子类中调用父方法foo,请使用:

If i want to call the parent method foo from child class i use:

[super foo]

如果我想打电话给祖父母的foo,我该怎么办?不能打电话

If i want to call grandparent's foo, how can i do? It's not possible to call

[super [super foo]]

蚂蚁的想法?

推荐答案

您当然可以使用父类的 help 完成此任务.如果您的 foo 调用 [super foo] ,而您的超类则依次调用 [super foo] ,因为它期望这种行为,那么一切都准备就绪.这是一种常见的模式(例如 -init -dealloc ).

You can, of course, accomplish this with the help of the parent class. If your foo calls [super foo] and your superclass then in turn calls [super foo] because it expects this behavior, then you're all set. This is a common pattern (e.g. -init and -dealloc).

但是您不能使用常规的Obj-C语法直接跳转.每个子类围绕其状态和方法为类定义自己的语义集.如果您可以在继承链上的任意位置任意调用实现,而中间实现却一无所知,那么任何实现都无法保证其自身状态的完整性,并且会破坏类周围的抽象.

But you can't jump directly using normal Obj-C syntax. Every subclass defines its own set of semantics for a class around its state and methods. If you could arbitrarily call implementations anywhere up your inheritance chain without the intermediate implementations knowing anything about it, then no implementation would have any guarantees about the integrity of its own state, and it would break the abstractions around classes.

换句话说,我讨厌被这样说的那个人,如果这似乎是您真正想要做的,那么您应该重新考虑您的设计.(如果是这样,请随时提出一个新问题来讨论您的对象模型的设计.这里的人们将很乐意为您提供帮助.)

In other words, and I hate being the guy that says this, you should rethink your design if this seems to be what you really want to do. (If so, feel free to open a new question to discuss the design of your object model. People here will be happy to assist.)

也就是说,从技术上讲,我怀疑您 可以通过直接处理Obj-C运行时来完成此任务.您可以获取对象的类引用,然后是其超类,然后是 its 超类,并从中获取所需的方法实现.然后与您的对象一起调用它.对此的代码是读者的练习.:) 此处是文档

That said, technically, I suspect you can accomplish this by dealing directly with the Obj-C runtime. You can get your object's class reference, then its superclass, then its superclass, and get the method implementation you want from it. Then call it with your object. Code for this is an exercise for the reader. :) Here are the docs.

这篇关于如何调用祖父母方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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