-viewDidLoad not called in subclassed UIViewController

前端 未结 3 2036
长发绾君心
长发绾君心 2020-12-29 14:32

Have patience with me, I\'m still learning Cocoa Touch. Other -viewDidLoad not being called question was unrelated to my issue, I did search.

I have FooViewCo

相关标签:
3条回答
  • 2020-12-29 14:33

    I have had this same problem twice. The first time, I forgot to connect the view of UITableViewController to the actual UITableView in interface builder. The second time, I forgot to make awakeFromNib call itself in the superclass.

    0 讨论(0)
  • 2020-12-29 14:46

    I have not found documentation to back up the following, but this is what I've deduced by experiment / experience:

    The viewDidLoad method is expected be called immediately after loadView is called, and it's up to whomever calls loadView to supply the extra call to viewDidLoad.

    In some cases, the SDK will handle this behavior for you. Suppose you have a subclass of UIViewController called MyViewController; then:

    • If you access myViewController.view before you call loadView, then the superclass accessor is smart enough to call loadView for you, and viewDidLoad immediately thereafter.

    As a result, if your code looks like this:

    MyViewController *myViewController = [[MyViewController alloc] init];
    [superView addSubview:myViewController.view];  // Calls viewDidLoad.
    

    then both loadView and viewDidLoad will be called on your behalf.

    However, if your code looks like this:

    MyViewController *myViewController = [[MyViewController alloc] init];
    [myViewController loadView];
    [superView addSubview:myViewController.view];  // Doesn't call viewDidLoad.
    

    then the view getter can see you've already loaded the view, and it assumes you also called viewDidLoad as well - so it doesn't call either. Ironically, the extra function call here prevents viewDidLoad from getting called.

    0 讨论(0)
  • 2020-12-29 14:58

    And I've answered my own question, so this may help future folks. Since I see viewDidLoad has, as its three top Googles in my suggest, "viewDidLoad not called", "viewDidLoad not getting called", and "viewDidLoad not firing", I imagine this is a usual mistake...

    Changing:

    fooViewController = [[FooViewController alloc] init];
    if(![[NSBundle mainBundle] loadNibNamed:@"FooViewController" owner:fooViewController options:nil]) {
        DebugF(@"Failed to load FooViewController");
        return;
    }
    

    To:

    fooViewController = [[FooViewController alloc] initWithNibName:@"FooViewController" bundle:[NSBundle mainBundle]];
    

    Fixed the problem. Obviously a mistake in how I'm using Cocoa.

    0 讨论(0)
提交回复
热议问题