Adding conflicting methods in an Objective C class using category
Asked Answered
L

2

4

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.

Laurettalaurette answered 8/6, 2011 at 11:29 Comment(0)
B
3

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.

Bettyebettzel answered 8/6, 2011 at 11:53 Comment(0)
D
3

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.

Dalliance answered 8/6, 2011 at 11:33 Comment(0)
B
3

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.

Bettyebettzel answered 8/6, 2011 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.