Home > Software design >  Why is this causing an unrecognized selector error?
Why is this causing an unrecognized selector error?

Time:04-05

    import UIKit
import Toolbar

class ViewController: UIViewController {
  
  lazy var toolbar: Toolbar = {
    let toolbar: Toolbar = Toolbar([
      Toolbar.Item(title: "BUTTON", target: nil, action: #selector(test(_:))),
      Toolbar.Item(title: "BUTTON", target: nil, action: nil),
      Toolbar.Item(title: "BUTTON", target: nil, action: nil)
    ])
    return toolbar
  }()
  
  
  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .systemBackground
    self.view.addSubview(self.toolbar)
  }
  
  @objc func test(_ sender: Any) {
    print("hello")
  }
}

After I press the first toolbar button the app crashes with:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull test:]: unrecognized selector sent to instance 0x1de715eb0'
terminating with uncaught exception of type NSException
CoreSimulator 802.6 - Device: iPhone 13 mini (41207433-2958-4380-93E0-D0448B566794) - Runtime: iOS 15.4 (19E240) - DeviceType: iPhone 13 mini
(lldb) 

I can't figure out how I am calling the test function incorrectly?

CodePudding user response:

Instead of:

Toolbar.Item(title: "BUTTON", target: nil, action: #selector(test(_:))),

Try:

Toolbar.Item(title: "BUTTON", target: self, action: #selector(test(_:))),
  • Related