I’m having a memory issue in my iPhone app. I'm using Monotouch. I have hunted down the problem, by using a static instance counters. The problem has something to do with modal view controllers. When i navigate from a root-viewcontroller to a first-level-viewcontroller and back, i find that the first-level-viewcontroller is garbage-collected. But when i make the first-level-viewcontroller modal by calling PresentModalViewController and i returning by calling DismissModalViewControllerAnimated, i find that the first-level-viewcontroller is not garbage collected. Not even when i call GC.Collect().
Why not? Am i doing something wrong?
What is the best practice for ensuring release of VC’s?
partial class RootViewController : UITableViewController
{
static int instanceCount;
static int nextId;
int instanceId;
public RootViewController (IntPtr handle) : base(handle)
{
instanceCount++;
instanceId = nextId++;
Console.WriteLine(string.Format("RootViewController #{0} Count={1}", instanceId, instanceCount));
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Root";
NavigationItem.RightBarButtonItem = new UIBarButtonItem("ModalVC", UIBarButtonItemStyle.Plain,
delegate
{
var firstlevelVc = new FirstLevelViewController();
PresentModalViewController(new UINavigationController(firstlevelVc), true);
});
NavigationItem.LeftBarButtonItem = new UIBarButtonItem("PushVC", UIBarButtonItemStyle.Plain,
delegate
{
var firstlevelVc = new FirstLevelViewController();
NavigationController.PushViewController(firstlevelVc, true);
});
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
GC.Collect();
}
~RootViewController()
{
instanceCount--;
Console.WriteLine(string.Format("RootViewController #{0} Count={1}", instanceId, instanceCount));
}
}
public partial class FirstLevelViewController : UIViewController
{
static int instanceCount;
static int nextId;
int instanceId;
public FirstLevelViewController (IntPtr handle) : base(handle)
{
Initialize ();
}
[Export("initWithCoder:")]
public FirstLevelViewController (NSCoder coder) : base(coder)
{
Initialize ();
}
public FirstLevelViewController () : base("FirstLevelViewController", null)
{
Initialize ();
}
void Initialize ()
{
instanceCount++;
instanceId = nextId++;
Console.WriteLine(string.Format("FirstLevelViewController #{0} Count={1}", instanceId, instanceCount));
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "1. level";
NavigationItem.RightBarButtonItem = new UIBarButtonItem("Dismiss modal",
UIBarButtonItemStyle.Plain,
delegate { ParentViewController.DismissModalViewControllerAnimated(true); });
}
~FirstLevelViewController()
{
instanceCount--;
Console.WriteLine(string.Format("FirstLevelViewController #{0} Count={1}", instanceId, instanceCount));
}
}