简体   繁体   English

Swift-init()中的UIButton.addTarget崩溃

[英]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... 在其他课程中,我尝试通过单击此按钮来执行doSomething(),但未成功,我的应用崩溃了...

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. 您的问题是,离开方法后,存储在局部变量testvar中的Test实例将被释放。 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. UIButton方法的addTarget不会保留其目标,因此不再有对Test实例的强大引用,它将被释放。 If you tap the button the system tries to call doSomething on the now deallocated instance. 如果点击按钮,系统将尝试在现在释放的实例上调用doSomething Which leads to a crash. 这导致崩溃。

You could store the instance in a instance variable of your UIViewController (or whatever object calls var testvar = ). 您可以将实例存储在UIViewController的实例变量中(或任何称为var testvar =对象)。

eg: 例如:

class FirstViewController: UIViewController {
    var testvar: Test!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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