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?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With