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.
fooMethod:
on a Baz
object, which
implementation will be called? The one inside the Foo+Bar
or the
one inside Baz
?I'm open to any good explanation and/or documentation.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With