Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
halileohalilei Avatar asked Jul 30 '15 07:07

halileohalilei


2 Answers

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.

like image 58
KPM Avatar answered Oct 09 '22 15:10

KPM


Did simple testing of your example, which showed that category's implementation is called on instance of Buz class even if I did not include header Foo+Bar anywhere, I used iPhone 6 simulator with iOS 8.1. Apple says that behaviour is unpredictable, so it is bad practice to do such coding.

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.

see, https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html Section Avoid Category Method Name Clashes

like image 22
Nik Yekimov Avatar answered Oct 09 '22 16:10

Nik Yekimov