UIView events and garbage collection

I watched something that could affect the memory consumption of any program, and I would like some thoughts.

I created a very simple test project with a UIViewController and a UINavigationViewController. I click on my ViewController and then I pop it up. The GC does this work, and my ViewController is freed (the destructor is called). But, if I create a UIButton, and I registered for one of its events (for example, TouchInsideUp), then my ViewController will not be released. I need to unregister an event in order to release my ViewController. To be sure that this is not a time issue, my test application has a button that calls GC.Collect ().

I do not understand that an object will be kept alive if it is accessible from the stack of any thread or static variable. If my ViewController has the right to garbage, then there will also be a UIButton. The event should not cause the ViewController to be stored in memory because the UIButton is not accessible by the GC. In my case, the ViewController only uses the NavigationController, so after it pops up, it should always be built.

With the help of the new profiler (mono 2.10), I may find a logical answer, but for now I am perplexed. Any ideas?

Edited . Here is the code to help understand my case.

My test ViewController is pretty simple

public class TestViewController : UIViewController{ ~TestViewController(){ Console.WriteLine("Finalizer called"); } public UIButton Button {get; set;} public override ViewDidLoad(){ base.ViewDidLoad(); // If I remove the event registering, my TestViewController is collected. Button = new UIButton(); Button.TouchUpInside += ButtonTouchEventHandler; View.AddSubview(Button); } void ButtonTouchEventHandler(object sender, EventArgs e){} } 

My MainWindow has a NavigationController and does the following:

  • He pushed a new instance of TestViewController (thus, only NavigationController has a reference to an instance of TestViewController)
  • TestViewController is displayed through the standard return button (if I do not register with TouchUpInside, the TestViewController finalizer is called)
  • When I return to MainWindow, the button allows me to simply call GC.Collect.
+4
source share
1 answer

Yes, there is a chance that the object graph will be blocked in this template, I fixed it in the next major version of MonoTouch (MonoTouch 4)

0
source

Source: https://habr.com/ru/post/1338496/


All Articles