ocanal ocanal - 5 months ago 31
iOS Question

InstantiateViewController calls ViewDidLoad

I have a classic master-detail logic and trying to create instance of detail UIViewController with InstantiateViewController inside a click event.

Here is my code,

MasterViewController.cs

detailButton += delegate {
UIStoryboard Storyboard = UIStoryboard.FromName ("Main", null);
Console.WriteLine("InstantiateViewController() started");
var profileController = Storyboard.InstantiateViewController("ProfileController") as ProfileController;
Console.WriteLine("InstantiateViewController() ended");
profileController.Id = 5;
};


ProfileViewController.cs

public partial class ProfileController : UIViewController
{
public int Id { get; set; }
public override void ViewDidLoad()
{
Console.WriteLine("ViewDidLoad() called");
}
}


When I click the button output is,

InstantiateViewController() started
ViewDidLoad() called
InstantiateViewController() ended


This means
profileController.Id
is set after
ViewDidLoad()
which means I can't load data by Id in ViewDidload event beacuse Id is null.

So my question is why
ViewDidLoad()
called by InstantiateViewController(), in which method should I load data by Id?

Thanks.

Answer

VoewDidLoad is called when the ViewController is loaded into memory.

So, the correct place to get the data is on ViewDidAppear. ViewDidAppear notifies the ViewController that its view was added to a view hierarchy.

UPDATE:

Based on the new information provided in comments you could do something like this:

public partial class ProfileController : UIViewController
{
    private int _id;

    public void SetupProfile (int id)
    {
        // Save the Id if necessary.
        _id = id;
        // Add event with this id related.
    }
    public override void ViewDidLoad() 
    { 
        Console.WriteLine("ViewDidLoad() called");
    }
}

In alternative if you still want to do the event setup in ViewDidAppear you could use this approach with the events:

yourClass.Event -= MyHandler;
yourClass.Event += MyHandler;