简体   繁体   中英

iOS View Controllers not being released?

(I'm using c#/Xamarin, but doubt the issue is specific to that.)

When I add a View Controller and then remove it - it's DidReceiveMemoryWarning is still called (in the Simulator and on real devices), so it can't have been released. I've narrowed it down to this:-

UIViewController vc=(UIViewController)this.Storyboard.InstantiateViewController(identifier);
this.AddChildViewController(vc);
vc.RemoveFromParentViewController();
vc=null;

and calling DidMoveToParentViewController and WillMoveToParentViewController (as described in the docs) doesn't help either:

UIViewController vc=(UIViewController)this.Storyboard.InstantiateViewController(identifier);
this.AddChildViewController(vc);
vc.DidMoveToParentViewController(this);
vc.WillMoveToParentViewController(null);
vc.RemoveFromParentViewController();
vc=null;

then simulate a memory warning and vc DidReceiveMemoryWarning gets called even though there is no reference to it. How is this possible when it's been removed as child controller and there is no reference to it.

(The same is happening when I use a segue set up in a Storyboard to go to a detail view in a UINavigationController, for example, after going "back" to the root controller, the detail controller still gets DidReceiveMemoryWarning messages.

Any help to understand this would be appreciated

UPDATE: Now the problem I have is with a simple UIViewController embedded in a UINavigationController

I add the navigation controller:

this.nc=(UINavigationController)this.Storyboard.InstantiateViewController("NavigationController");
this.AddChildViewController(this.nc);
this.nc.DidMoveToParentViewController(this);

and remove later (after it's loaded):

this.nc.WillMoveToParentViewController(null);
this.nc.RemoveFromParentViewController();
this.nc=null;

and this all works fine (it's not retained). BUT if I add this simple line in the ViewDidLoad method of the ViewController thats embedded, then the ViewController IS retained!

Console.WriteLine("this.NavigationController={0}",this.NavigationController);

ie, just accessing "this.NavigationController" causes the VC to be retained!

So each time I run it, I get another ViewController retained!

Any ideas?

It could be that your view controller's initialization method has some side effect causing it to stay alive. A common example would be that it creates an NSTimer object, which retains its target. Go through the methods that are called when the view controller is instantiated from the storyboard and see if anything retains it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM