Search code examples
iphoneuiviewcontrollerloadview

self.view = aViewController.view vs [aViewController loadView] -


I am trying to understand the behavior of view controllers when switching from one to another (displaying different views)

A part form the addSubiew statements which seem to work, I can't find an explanation to what happens with the two statements:

self.view = someViewController.view; [someViewController loadView];

In fact I got a case where only the first one seems to work (the view defined within someViewController is displayed) and in another case only the second one.

More precisely, from the root viewController.view to anotherViewController.view (already istantiated) I have to use the first one, to come back I need to use the second one. I can't understand what can it be the difference in the current situation which allows one or the other statement to work.

Thank you


Solution

  • Looks like you have some misconceptions about how view controllers work.

    There are a couple things wrong with those 2 statements:

    self.view = someViewController.view;
    

    According to the docs of UIViewController.view :

    "Each view controller object is the sole owner of its view. You must not associate the same view object with multiple view controller objects." -Apple Docs

    Once that line of code executes, the view would have 2 different controllers, which is bad.

    Next line:

    [someViewController loadView];
    

    This is bad because you should never explicitly call loadView.

    From the docs of UIViewController.loadView :

    "You should never call this method directly."

    From the docs of UIViewController.view :

    "If you access this property and its value is currently nil, the view controller automatically calls the loadView method and returns the resulting view. "

    Spend some time with the viewController tutorials and guides such as "View Controller Programming Guide for iPhone OS". They are good docs and can teach a lot.