【发布时间】:2016-01-02 06:46:22
【问题描述】:
在下面的代码中,我有两个按钮。
button1 是可选的,它被赋予了从父视图中移除自身的功能。
button2 被分配了一个将 button1 添加到 superview 的函数,并展开了 button1 的可选类型。
我希望在调用.removeFromSuperview()之后从内存中释放button1,这样当你点击button1后点击button2时,app会崩溃:
var button1: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
var frame1 = CGRectMake(100, 150, 150, 40)
button1 = UIButton(frame: frame1)
button1!.setTitle("remove button 1", forState: .Normal)
button1!.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.view.addSubview(button1!)
button1!.addTarget(self, action: "remove:", forControlEvents: .TouchUpInside)
let frame2 = CGRectMake(100, 250, 150, 40)
let button2 = UIButton(frame: frame2)
button2.setTitle("display button 1", forState: .Normal)
button2.setTitleColor(UIColor.blueColor(), forState: .Normal)
button2.addTarget(self, action: "display:", forControlEvents: .TouchUpInside)
self.view.addSubview(button2)
}
func remove(sender: UIButton){
button1?.removeFromSuperview()
}
func display(sender:UIButton){
self.view.addSubview(button1!)
}
当我单击 button1 时,它会从 superview 中删除。但是,当我单击 button2 时, button1 会返回到 superview 而不被初始化。
调用button1?.removeFromSuperview()后是否需要在remove函数中调用button1 = nil?如果不是,按钮 1 是否在某个特定阶段从内存中释放?
【问题讨论】:
-
Fan Zhang,请不要通过恢复有效更改来搞乱这个问题。代码区域不需要引用,标题中不需要
Swift,因为您已经有一个标签可以将问题放在正确的类别中。
标签: swift memory-management uiview uiviewcontroller uibutton