我有一个自定义 UIButton 并想在按下它后将其删除。但是当我尝试这样做时,不知何故没有调用 deinit 。我在一个空项目中试过这个:
class CustomButton: UIButton {
deinit { print("deinit") }
}
class ViewController: UIViewController {
var button: CustomButton!
override func viewDidLoad() {
super.viewDidLoad()
button = CustomButton(frame: CGRectZero)
button.translatesAutoresizingMaskIntoConstraints = false
let views = ["button": button]
view.addSubview(button)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[button]", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[button]-50-|", options: [], metrics: nil, views: views))
button.backgroundColor = .redColor()
button.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
// button.removeFromSuperview()
// button = nil
}
func pressed(sender: UIButton) {
button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
button.removeFromSuperview()
button = nil
}
}
如果我直接在 中删除它viewDidLoad()
,将调用 deinit,但是每当我使用如上所示的代码时,什么都不会显示。我怎样才能让它调用deinit?这是否意味着它没有被释放或者只是没有被调用 deinit ?