Aaban Tariq Murtaza
Aaban Tariq Murtaza

Reputation: 1252

Category Or Extention -- Which one will have precedence

I write awakeFromXib in UILabel category plus Swift UILabel extension. Now I add one brand new UILabel on ViewController (no outlet created).

awakeFromNib is being called from the category and not from Swift extension.

Please guide which one will have precedence and in what circumstances.

enter image description here

Note: ViewController parent class is written in Swift.

Upvotes: 0

Views: 79

Answers (1)

Aleksandr Medvedev
Aleksandr Medvedev

Reputation: 8958

First of all - neither Swift extensions nor Objective-C categories should be used to override non-inherited methods (methods already defined in the class being extended). Apple mentions it in both Swift Developer Guide..:

Extensions can add new functionality to a type, but they can’t override existing functionality.

..And Programming with Objective-C documentations:

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 look for a written "contract", it's emphasised in the quoted text above: if a method is defined in an extensions of a Swift class which itself is a subclass of NSObject (and UILabel is indirect subclass of NSObject) it gets dispatched with messaging mechanism (just like a method defined in an Objective-C category). Thus both methods follow the same Objective-C rules, dispatched the same way, have the same name and the same set of arguments. According to the Apple's own documentation in regards to Objective-C categories it means that the behavior is undefined.

You can probably find empirically some general pattern, but it is not guaranteed to be consistent (can work differently between or even within the same application session) and is a subject to change in future releases.

P.S. It's also double-discouraged to "shadow" Cocoa/Cocoa touch framework classes methods since you may end with suppressing the class own implementation from being called and consequently breaking the dependent logic.

Upvotes: 3

Related Questions