Thanos
Thanos

Reputation: 854

Getting EXC_BAD_ACCESS when UIButton calls its selector action

I have this code and I am trying to assign an action to the UIButton in the view, with ultimate goal to make it execute a passed closure. However, the app crashes ungracefully when I tap the button and tries to call the action assigned to it.

In particular it shows the class AppDelegate: UIResponder, UIApplicationDelegate line with the error Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT). I am guessing it's something about what Swift calls safety...probably doing something wrong with explictly unwrapped optionals?

Any ideas?

import Foundation
import UIKit

class GenericCustomPopupViewController: UIViewController {
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var popupTitleLabel: UILabel!
    @IBOutlet weak var popupBodyLabel: UILabel!
    @IBOutlet weak var okayButton: UIButton!

   // var okayButtonAction: (()->Void)!

    override func viewDidLoad() {

        okayButton.layer.cornerRadius = 17
        okayButton.layer.borderWidth = 1
        okayButton.layer.borderColor = UIColor(red: 195/255, green: 33/255, blue: 121/255, alpha: 1).CGColor

    }

    func showPopupInView(rootView:UIView) {

       // self.okayButtonAction = completion
        self.view.frame = rootView.bounds
        rootView.addSubview(self.view)

        self.okayButton.addTarget(self, action:"buttonTapped:", forControlEvents:.TouchUpInside)

        self.containerView.center.y = -400
        self.containerView.alpha = 0

        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2, options: UIViewAnimationOptions.CurveEaseInOut, animations: ({
        self.containerView.center.y = rootView.center.y
        self.containerView.alpha = 1
    }), completion: nil)

}

    func hidePopupView() {
        self.view.removeFromSuperview()
    }

    func buttonTapped(sender: UIButton!) {
       println("test")
    }


}

This UIViewController is instantiated like this in the parent view:

var permissionsPopup = GenericCustomPopupViewController(nibName:"LocationPermissionsInfoView", bundle: nil)
    permissionsPopup.showPopupInView(self.view)

Upvotes: 1

Views: 423

Answers (1)

Thanos
Thanos

Reputation: 854

Ah, found it.

The permissionsPopup reference to GenericCustomPopupViewController was being deallocated after the .showPopupInView(). I solved it by making a strong reference to it and deallocating later when I no longer needed it.

Upvotes: 1

Related Questions