简体   繁体   中英

Swift - Crash when UIButton.addTarget in init()

class Test: NSObject {

init(mainView:UIView){
   super.init()
   var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
   button.setTitle("Test", forState: UIControlState.Normal)
   button.backgroundColor = UIColor.whiteColor()
   button.frame = CGRectMake(0, 0, 250, 40)
   button.addTarget(self, action: "doSomething", forControlEvents: UIControlEvents.TouchUpInside)
   mainView.addSubview(button)
}
func doSomething(){
   println("test")
}
}

in other class I try to doSomething() by clicking this button, but unsuccessfully my app crash...

var testvar = Test(view)

How to trigger this function by button pressed without app crash ?

It's a memory management issue. Your problem is that the Test instance you stored in the local variable testvar will be released after you left the method. The addTarget of UIButton method does not retain it's target, so there are no more strong references to the Test instance and it will be deallocated. If you tap the button the system tries to call doSomething on the now deallocated instance. Which leads to a crash.

You could store the instance in a instance variable of your UIViewController (or whatever object calls var testvar = ).

eg:

class FirstViewController: UIViewController {
    var testvar: Test!

    override func viewDidLoad() {
        super.viewDidLoad()
        testvar = Test(mainView:self.view)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM