CALayer 的子类 VS 类别

发布于 2024-12-17 15:58:33 字数 266 浏览 1 评论 0原文

如果我子类化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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萧瑟寒风 2024-12-24 15:58:33

在类别中调用 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 to CALayer's superclass, which is NSObject.

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文