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!
If I subclass a CALayer and override the drawInContext: method everything is great. If
Share
Calling the
superimplementation 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
superimplementations 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?