Martin Babacaev
Martin Babacaev

Reputation: 6280

Extending a class using categories with identical methods name

I want to extend a class using category NSArray+Populate.h:

@interface NSArray (Populate)
-(NSArray *) populateArray; 
@end

How can I detect the situation if there is another category (from another module or library), extending NSArray with method having the same name ?

For example, if there is a NSArray+Fill.h:

@interface NSArray (Fill)
-(NSArray *) populateArray; 
@end

As I understand, the run-time engine will choose one of the version silently, without any crash ?

Upvotes: 3

Views: 1297

Answers (1)

user557219
user557219

Reputation:

You cannot detect this situation and you cannot determine which implementation of -populateArray takes precedence. Some developers prefer to prefix their category method names for this reason.

Quoting 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 since 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.

Upvotes: 7

Related Questions