调用view.removeFromSuperview() 后是否需要将view 设置为nil?

Fan*_*ang 5 memory-management uibutton uiviewcontroller uiview swift

在下面的代码中,我有两个按钮。

button1 是可选的,它被分配了从超级视图中删除自己的功能。

button2 被分配了一个函数,将 button1 添加到 superview,解包 button1 的可选类型。

我希望在调用之后从内存中释放 button1 .removeFromSuperview(),这样当你点击 button1 后点击 button2 时,应用程序会崩溃:

  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!)
  }
Run Code Online (Sandbox Code Playgroud)

当我单击 button1 时,它会从超级视图中删除。但是,当我单击 button2 时,button1 未初始化就返回到超级视图。是否有必要呼吁button1 = nilremove调用函数后button1?.removeFromSuperview()?如果没有, button1 是否在某个阶段从内存中释放?

小智 5

看一下这个例子,你就会明白为什么button1被从 中删除view但它没有从内存中释放,因为从 中删除后保留计数仍然是 1 view

// Retain count is 1
let button1 =  UIButton(frame: frame1)

// Retain count is 2
self.view.addSubview(button1)

// Retain count is 1 again
 button1.removeFromSuperview()
Run Code Online (Sandbox Code Playgroud)


小智 5

这实际上取决于。

如果您的 UIView 实例未分配给其他指针,因此不会增加引用计数,removeFromSuperView 会将引用减少到 0,然后将其释放。在其他情况下,uiview 仍然存在其他强引用。

否则,如果要直接释放引用,则需要 uiview = nil。