Reputation:
The following code doesn't seem to work for me.
class SomeSubView: UIView {
deinit {
removeFromSuperview()
}
}
let view = UIView()
var subview: SomeSubView! = SomeSubView()
var subview2: SomeSubView! = SomeSubView()
view.addSubview(subview)
view.addSubview(subview2)
subview = nil
subview = SomeSubView()
view.addSubview(subview)
print(view.subviews) //contains three views, should contain two
I also had a print()
inside the deinit, so I'm pretty sure it is called. I could call subview.removeFromSuperview()
before making the expression subview = nil
, that works fine.
I'm only curious why this limitation exists, what kind of stuff can not be done inside deinit
? I feel what I'm trying to do should work ...
Upvotes: 1
Views: 1159
Reputation: 385590
It is never necessary to call removeFromSuperview()
on self
in deninit
. A superview retains its subviews, so it's impossible for a view to be deallocated while it is a subview.
Setting subview = nil
does not deallocate the object referenced by subview
. It simply stops making subview
reference that object.
Upvotes: 3