swiftoverridingunrecognized-selectorclass-extensions

Property "isEnabled" of UIBarButtonItem is an unrecognized selector in an extension of the class


In Swift 4 I want to use an extension of UIBarButtonItem that instantiates a special UIBarButtonItem object.
Here is my code (only the essential statements):

import Foundation

extension UIBarButtonItem {

    convenience init(staticImageName: String) {
        let staticView = UIImageView.init(image: UIImage(named: staticImageName))
        self.init(customView: staticView)
//      further code…
    }

    override open var isEnabled: Bool { 
        didSet { 
            print("didSet called") // Should be replaced by other code…
        } 
    } 

} // extension UIBarButtonItem

This extension builds without problems.

However when I run the app, I get a runtime error at the statement
self.init(customView: staticView).
The log says:

-[UIBarButtonItem isEnabled]: unrecognized selector sent to instance 0x7fe20c505180

What is wrong with my code?


Solution

  • Extensions are not supposed to be used to override any existing functionality. Extensions are only supposed to be used to add new functionality.

    For the Extensions chapter in the Swift book:

    “Extensions can add new functionality to a type, but they cannot override existing functionality.”

    So the proper solution is to subclass UIBarButtonItem if you wish to override existing functionality. Then use the subclass wherever you need it.