Search code examples
objective-cinheritanceobjective-c-category

Call precedence for method overridden in category and again in subclass


I'm working on a project in Objective-C and I'm facing a situation.

Let's say I have a class named Foo. I implement a category for this class named Foo+Bar and override Foo's method fooMethod:.

Then I create a subclass for Foo, named Baz and override the same fooMethod: in this class.

  1. When I use the method fooMethod: on a Baz object, which implementation will be called? The one inside the Foo+Bar or the one inside Baz?
  2. How does Objective-C handle this situation and why?

I'm open to any good explanation and/or documentation.


Solution

  • Behaviour if you override a method in a category is explicitly undefined. So please don't:

    If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime.

    If you were overriding a method defined once in a category of the superclass then of course the subclass implementation would be called.

    But here you override a method defined twice in the superclass. Behaviour is likely to be undefined, because you override an undefined implementation. Even if this worked, it would be bad code anyway.

    Really, please don't do this.