Priority call for a method overridden in a category and again in a subclass

I am working on a project in Objective-C and I came across a situation.

Say I have a class called Foo . I am implementing a category for this class named Foo+Bar and overriding the Foo method fooMethod:

Then I subclass Foo with the name Baz and override the same fooMethod: in this class.

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

I am open to any good explanation and / or documentation.

+5
source share
2 answers

The behavior if you override a method in a category is clearly undefined . Therefore, do not do this:

If the name of the method declared in the category is the same as the method in the source class, or the method in another category in the same class (or even in the superclass), the behavior is undefined for which the method is used at runtime.

If you override a method defined once in the superclass category, then, of course, the implementation of the subclass is called.

But here you are redefining a method defined twice in a superclass. The behavior is likely to be undefined because you are redefining the implementation of undefined. Even if this works, it will be bad code anyway.

In fact, please do not do this.

+6
source

A simple check of your example, which showed that the category implementation calls an instance of the Buz class, even if I did not use the Foo + Bar header anywhere, I used the iPhone 6 simulator with iOS 8.1. Apple says the behavior is unpredictable, so doing such an encoding is bad practice.

If the name of the method declared in the category is the same as the method in the source class, or the method in another category in the same class (or even in the superclass), the behavior is undefined for which the method is used at runtime.

see https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html Section Avoid Parsing a Method Class Name

+1
source

All Articles