Gian Marco Toso
Gian Marco Toso

Reputation: 12136

Subclass VS Category for CALayer

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!

Upvotes: 1

Views: 646

Answers (1)

jrturton
jrturton

Reputation: 119242

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?

Upvotes: 2

Related Questions