Search code examples
c#iosxamarin.iosxamarinuisearchdisplaycontroller

Why does UISearchDisplayController has to be a class variable?


I'm using Xamarin iOS.

In ViewDidLoad I'm instantiating my UISearchBar, UISearchDisplayController, UISearchDisplayDelegate and UITableViewSource. Thereby I'm using a class variable for the UISearchDisplayController. Because I only used it in ViewDidLoad I moved the class variable for UISearchDisplayController to a local variable.

Now the strange things happened:

  • The search didn't worked anymore. Regardless of my input nothing changed.
  • Also the searchbar didn't moved to the navigation bar as it is the standard behavior.

Now I reverted my changes back and it works again. I checked my code and there is nothing different than this.

But why can I use UISearchDisplayController only as class variable?

Edit:

@class variable:

namespace MyApp
{
    partial class MyTableListController : UITableViewController
    {
        // class variable
        private UISearchDisplayController searchController;

        public MyTableListController (IntPtr handle) : base (handle)
        {
            // do some init
        }

        #region View lifecycle

        public override void ViewDidLoad (){
            // ..
        }
    }
}

Seems that the controller is not only used in ViewDidLoad and therefore must be available in the whole class (e.g. class variable).


Solution

  • If you make the search controller a method variable, the garbage collector is free to collect it once the method finishes.

    You must ensure you keep a reference to the search controller as long as it's in use.