nontomatic nontomatic - 4 years ago 125
Swift Question

Segmented control addTarget() crashing app below iOS 9.0

My app has been released recently but it supports iOS 8.2.

Unfortunately, below iOS 9.0 tapping a segmented control which has been added programmatically crashes the app with no error message in the console.

I believe that the line where the target is added may cause the issue:

The following line is placed inside the init() of my custom cell, the segmented control is an instance var and calls a method in its parent view controller

segmentedControl.addTarget(ListViewController(), action: #selector(ListViewController.segmentedControlToggled(segmentedControl:)), for: .valueChanged)

Again, this works as expected down to iOS 9.0.

The setup works fine, it only crashes once the segmented control is tapped.

Should there be another syntax for the selector?

Thanks for any suggestions!

Answer Source

Per the documentation of addTarget:

The control does not retain the object in the target parameter. It is your responsibility to maintain a strong reference to the target object while it is attached to a control.

Which means that you need to store the value of the target parameter somewhere, thing you fail to achieve:


The ListViewController will get deallocated as soon as there will be no other references to it, the important thing to remember here is that you can't know in advance when the deallocation will happen, as you don't know how may other objects will refer your.

To make sure the target doesn't get deallocated, store the ListViewController instance into a property.

The crash is not particular to the iOS version, it might be that on some iOS version the ListViewController gets deallocated sooner.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download