Reece Kenney
Reece Kenney

Reputation: 2964

UIButton calls function from wrong class

I have a ButtonProvider class that creates my button and adds a target action. However, when the button is pressed, it doesn't call the function from the ButtonProvider class in which it was created, but instead calls a function with the same name from the other class.

class ButtonProvider {

    let view: UIView!
    let button: UIButton!

    init(view: UIView) {
        self.view = view
    }

    func showButton() {
        button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        button.backgroundColor = .white
        button.addTarget(self, action: #selector(ButtonProvider.close), for: .touchUpInside)

        view.addSubview(button)
    }

    @objc func close() {
        button.removeFromSuperview()
    }

}

And in my calling ViewController:

override func viewDidLoad() {
    let buttonProvider = ButtonProvider(view: self.view)
    buttonProvider.showButton()
}

@objc func close() {
    //This is the function that is called
}

Any ideas why a selector of ButtonProvider.close calls my ViewController.close function?

Upvotes: 1

Views: 91

Answers (1)

Sulthan
Sulthan

Reputation: 130102

You buttonProvider is not owned by the controller therefore it will be deallocated as soon as viewDidLoad ends. When the button is pressed the instance does not exist in memory any more and the result will be undefined behavior, usually a crash.

You will have to save buttonProvider to a strong property in the controller.

Upvotes: 1

Related Questions