Have a look at the sample below which is not completely implemented but demonstrates what I'm talking about:
public class MyClass : UIView
{
private UIView SubView;
private UILabel ALabelInTheSubView;
public override ViewDidLoad()
{
}
// Imagine our view has a button. When clicked, a new sub view is added.
public void HandleButtonAddView()
{
// Assign a new view to the SubView member and add a label.
this.SubView = new UIView();
this.ALabelInTheSubView = new UILabel("A label");
this.SubView.AddSubView(this.ALabelInTheSubView);
// Add the SubView to myself.
this.AddSubView( this.SubView );
}
// Imagine our view has another button. When clicked, the sub view is removed.
public void HandleButtonRemoveView()
{
this.SubView.RemoveFromSuperView();
}
}
- If I click the button to add the subview, the member variables
SubView
andALabelInTheSubView
are assigned new instances ofUIView
andUILabel
. - If I then click the button to remove the subview,
SubView
gets removed from super view. - After
this.SubView.RemoveFromSuperView()
the membersSubView
andALabelInTheSubView
still have references to the view or label, hence no memory will be released yet. Correct so far? - If I now click the button to add the sub view again, the members will be overwritten with NEW instances of
UIView
andUILabel
.
QUESTION: Does the GC now know that it can now safely dispose the previously assigned UIView
and UILabel
? I mean, all references should be gone. Or do I have to call this.SubView.Dispose() and this.ALabelInTheSubView.Dispose()
after removing from superview? And is disposing the label necessary at all, since it is a child node of the UIView, which just got removed and disposed (which would mean I always have to dispose from bottom to top)?
ADD. SIDE-QUESTION: If I call Dispose() on an object this IS still referenced - is that a a problem?