Search code examples
xcodeswiftexc-bad-access

swift error exc_bad_access loading image using iboutlet


I'm new in iOS-programming. I tried the following. I created a custom class for a button (source founded on internet) like.

class CustomButton : UIButton {

var myAlternateButton:Array<CustomButton>?
var downStateImage:String? = "radiobutton_down"{

    didSet{

        if downStateImage != nil {

            self.setImage(UIImage(named: downStateImage!), forState: UIControlState.Selected)
        }
    }
}

Now when i try to use the class in my TableViewController I get the error mentioned above

class SettingsTableViewController: UITableViewController {

@IBOutlet var testButton: CustomButton?
@IBOutlet var excelButton: CustomButton?
override func viewDidLoad() {
    super.viewDidLoad()
    testButton?.downStateImage = "radiobutton_down" -->xc_bad_access

why I can not set the property. Do I have to initialize the class separately or where is my error? Perhaps anyone can help me! Thanks, arnold


Solution

  • Have you linked your outlet correctly with your UIButton on your interface builder? Be sure to set your custom class name on your custom view too, like so:

    CustomView

    Also, if you're setting views using the IBOutlet system I would recommend defining them like this instead if the views are always present:

    @IBOutlet weak var testButton: CustomButton!
    @IBOutlet weak var excelButton: CustomButton!