简体   繁体   中英

UIViewController viewDidLoad called before init method is complete

I have a view controller that initializes two other view controllers. The view for one controller wasn't showing, and I tracked the problem to the instance being nil when it's added to the superview.

Here is the code. viewDidLoad is being called before the favoritesTableVC is initialized. I can see this by placing breakpoints in the initialization methods of the resultsTableVC and favoritesTableVC view controllers.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        resultsTableVC = [[[ResultsTableVC alloc] initWithController:self andTableView:nil] retain];
        favoritesTableVC = [[[FavoritesTableVC alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, defaultFavoritesTableHeight) andController:self] retain];        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view addSubview:resultsTableVC.view];
    [resultsTableVC release];
    [self.view addSubview:favoritesTableVC.view];
    [favoritesTableVC release];    
}

Here is the order the methods are being called:

  • allResults init
  • resultsTableVC init
  • allResults viewDidLoad
    • addSubview allResultsVC
    • addSubview favoritesResultsVC
  • favoritesResultsVC init

This is a single thread, so I don't understand how viewDidLoad can be called before init is complete.

-[ResultsTableVC initWithController:andTableView:] is probably referencing allResults.view.

This would force the allResults controller to load its view (which then of course causes viewDidLoad to fire). All of this happens synchronously, before you actually return from initWithController:andTableView:

I'm taking a guess, but could you try this :

favoritesTableVC = [[[FavoritesTableVC alloc] initWithFrame:CGRectMake(0, 10, SOME_HARD_CODED_INT, SOME_HARD_CODED_INT) andController:self] retain]; 

And see if you get the same result.
My guess is that self.view is pointing to nil at that time.
But that wouldn't explain why the init is call after... but no harm in trying.
(I haven't tested it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM