CALayer 的子类 VS 类别
如果我子类化CALayer
并重写drawInContext:
方法,一切都很好。如果我为 CALayer 创建一个类别,其中我重写相同的方法(作为子类化的替代方法),它会被调用,但不会绘制任何内容。当然,在这两种情况下都会调用[super drawInContext:ctx]
。为什么?
我对子类化没有问题,我只是好奇为什么会发生这种情况。我的印象是类别可用于添加或覆盖任何类的方法,作为创建整个子类的替代方法。
谢谢你!
If I subclass a CALayer
and override the drawInContext:
method everything is great. If I create a category for CALayer
where I override the same method (as an alternative to subclassing), it gets called but it doesn't draw anything. Of course, the [super drawInContext:ctx]
is called in both cases. Why?
I have no problem with subclassing, I'm just curious as to why this happens. I was under the impression that categories could be used to add or override methods for any class, as an alternative to creating a whole subclass.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在类别中调用 super 实现会在您拥有该类别的对象的超类上调用它们,而不是您想要执行的原始对象实现。
super
在实例方法中的方法调用上下文中使用时,将调用该方法的超类实现。在类别中,您尚未创建子类 - 您编写的代码将直接由您拥有该类别的类直接执行。因此,对
super
实现的调用将被发送到CALayer
的超类,即NSObject
。因此,我对您在类别中尝试此操作时没有收到编译器警告感到有点惊讶。
这里对此有进一步精彩的讨论:在类别中调用 super 和在子类中调用它一样吗?
Calling the
super
implementation in a category calls them on the superclass of the object you have the category against, not the original object implementation which is what you are trying to do.super
, when used in the context of a method call in an instance method, calls the superclass's implementation of that method.In a category, you haven't made a subclass - the code you have written is being executed directly by the class you have the category against. Therefore calls to
super
implementations will be sent toCALayer
's superclass, which isNSObject
.I'm therefore a little surprised that you didn't get compiler warnings when attempting this in the category.
There is further excellent discussion of this here: Is calling super in a category the same as calling it in a subclass?