341008
341008

Reputation: 10222

Adding conflicting methods in an Objective C class using category

I have added a method foo to a class MYCustomClass in a category Category1 separate from the original definition of the class. Then I added another method also called foo in another category Category2. I then call foo on an instance of MYCustomClass. In my case the foo in Category2 is being called. My question is: Is there any explanation for this? Or, is it one of those "undefined"/"compiler dependent" behaviours. Also, is it possible to handle such situations by qualifying the method call by specifying the category I want to be used in the call.

EDIT: I am aware that what I am doing is not supported. I am just interested in if there is a hack around it.

Upvotes: 4

Views: 1248

Answers (2)

NSResponder
NSResponder

Reputation: 16857

When a category is loaded, its methods are inserted into the existing method table, and there's no way to distinguish where they came from once that's done. The last category to load wins. Back in the NeXTSTEP days, we would sometimes do this deliberately as a very kludgey way to fix a broken method in code for which we didn't have the source.

Upvotes: 3

user557219
user557219

Reputation:

It’s undefined behaviour. From the Objective-C Programming Language document:

A category cannot reliably override methods declared in another category of the same class.

This issue is of particular significance because many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.

And no, you cannot specify that you want foo from Category1, or foo from Category2. If you need this, you should give different names to those methods, e.g. foo1 and foo2.

Upvotes: 3

Related Questions