可可爷爷
是否可以访问对象超类(或祖父)的超类方法?
例如:
GrandFatherObject : NSObject
SuperObject : GrandFatherObject
SelfObject : SuperObject
来自 SelfObject:
- (void)overriddenMethod
{
// For Self
someCode();
// For Parent
[super overriddenMethod];
// For GrandParent
???
}
我只能访问 SelfObject(无法修改 SuperObject 或 GrandFatherObject)
Is it possible to access the super class method of an objects super class (or grandfather)?
For instance:
GrandFatherObject : NSObject
SuperObject : GrandFatherObject
SelfObject : SuperObject
From SelfObject:
- (void)overriddenMethod
{
// For Self
someCode();
// For Parent
[super overriddenMethod];
// For GrandParent
???
}
I only have access to SelfObject (Can't modify SuperObject or GrandFatherObject)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以做到这一点,但它需要的代码比仅仅调用
super
多一点。或多或少,它会是这样的:
Yes, you can do it, but it takes a bit more code than just invoking
super
.More or less, it'd be something like this:
你为什么要这样做?如果您认为有必要,您应该重新考虑您的类设计。当然,您始终可以在父类的
overriddenMethod
实现中调用super
。为了正确封装,子类不需要了解除父类之外的任何信息。否则,继承层次结构中就会出现紧密的双向耦合。噩梦。
Why would you want to do this? You should rethink your class design if you think this is necessary. You can always, of course, call
super
in the parent class's implementation ofoverriddenMethod
.For proper encapsulation, subclasses shouldn't need to know about anything other than their parent class. Otherwise you have tight, bi-directional coupling within the inheritance hierarchy. Nightmares.
虽然使用 objc_msgSendSuper() 当然很有趣,但为什么不采取简单的方法并在 SelfObject 实现中创建一个类别,就像
你说你不能修改 SuperObject,这并不意味着你不能扩展它。我在这里遗漏了任何主要缺点吗?
While playing with objc_msgSendSuper() is certainly fun, why don't you take the easy way and create a Category in the SelfObject implementation, something like
You said you can't modify SuperObject, that doesn't mean you can't extend it. Am I missing any major drawbacks here?