One of the nice things about Visual Studio 2012 is the Code Analysis. It’s worth doing to try and find underlying problems and I found some in mine. The code worked fine, but Code Analysis told me I was doing naughties with a Virtual Method in a constructor.

Mea culpa. I was indeed. I’d created a View object with my Subclassed View in a CustomViewController.

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            View = new MainView(UIScreen.MainScreen.Bounds);
        }

But I’d been doing all sorts in the MainView() constructor that needed not to be there, though it had seemed to run ok. If configuration data is absent I want to stop things and have it entered. So I was creating SubViews (Controls) and then calling the UIView.AddSubView() that MainView inherited from within the Constructor. Shock Horror Probe! Bad Code Alert…

The risk is that a virtual method may not have been correctly assigned and the compiler doesn’t really like Constructors in C# to have to worry about this. After a Constructor has finished, things should be just swell.

The trick is to move the code into a subclassed ViewController.ViewWillAppear(). This is called whenever the View is about to appear. Use a bool variable to let things that should be initialized here just the once be only called just the once.

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            if ((View as MainView).ConfigCheck() && OneOff)
            {
                OneOff = false;
                // one off code here
            }
        }