10

I have read many tutorials and even the official Apple documentation and must not understand what is wrong with this code.

var dueDatePicker = UIDatePicker()

@IBOutlet weak var textField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    textField.inputView = dueDatePicker
    dueDatePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
}

func datePickerValueChanged(_ sender: UIDatePicker){
    //Do Stuff
}

At runtime, I click on the textField and the UIDatePicker appears. The function that the selector points to is executed. As soon as I click a UI object outside of the UIDatePicker, the app crashes with this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[YourApp.PromiseViewController dueDateChanged:]: unrecognized selector sent to instance 0x100b12ae0'

What I don't understand is that the "selector" or pointer to the desired function is recognized initially. However, when I trigger another event from another UI Object this exception is thrown.

Why is this happening?

Shouldn't this exception be triggered when datePickerValueChanged() is called initially?

Kohler Fryer
  • 764
  • 2
  • 8
  • 17

2 Answers2

8

Just add @objc in front of your function

@objc func datePickerValueChanged(_ sender: UIDatePicker){
    //Do Stuff
}
Leang Socheat
  • 1,156
  • 2
  • 12
  • 23
5

The error is telling you that an action with the selector dueDateChanged(_:) has been added as a target action.

More than one target action can be added to a control. Somewhere, maybe in your storyboard or xib, you have another action added to dueDatePicker.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117