Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to set view to nil after calling view.removeFromSuperview()?

In the code below I have two buttons.

button1 is optional, it is assigned with the function to remove itself from superview.

button2 is assigned a function which adds button1 to superview, with unwrapping the optional type of button1.

I hope to deallocate button1 from memory after calling .removeFromSuperview(), so that when you click button2 after clicking button1, the app will crash:

  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!)
  }

When I click button1, it is removed from superview. However when I click button2, button1 is back to superview without being initialized. Is it necessary to call button1 = nil in remove function after calling button1?.removeFromSuperview()? If not, is button1 deallocated from memory at some certain stage?

like image 566
Fan Zhang Avatar asked Jan 02 '16 06:01

Fan Zhang


2 Answers

This actually depends.

If your UIView instance is not assigned to other pointers, thus not incrementing the reference count, removeFromSuperView will decrement the reference to 0, and it is released. In other cases, uiview is still alive with other strong references.

Otherwise, you need uiview = nil if you want to release the reference directly.

like image 152
godzilla Avatar answered Nov 19 '22 11:11

godzilla


Take a look at the example so you can understand why the button1 is removed from the view but it has not deallocated from memory because the retain count still is 1 after being removed from the 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()
like image 5
Kiet Nguyen Avatar answered Nov 19 '22 10:11

Kiet Nguyen