【问题标题】:Is it necessary to set view to nil after calling view.removeFromSuperview()?调用 view.removeFromSuperview() 后是否需要将 view 设置为 nil?
【发布时间】: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


【解决方案1】:

这实际上取决于。

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

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

【讨论】:

    【解决方案2】:

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

    // Retain count is 1
    let button1 =  UIButton(frame: frame1)
    
    // Retain count is 2
    self.view.addSubview(button1)
    
    // Retain count is 1 again
     button1.removeFromSuperview()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      相关资源
      最近更新 更多