简体   繁体   English

在初始化方法完成之前调用的UIViewController viewDidLoad

[英]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. 在初始化favoriteTableVC之前,将调用viewDidLoad。 I can see this by placing breakpoints in the initialization methods of the resultsTableVC and favoritesTableVC view controllers. 通过在resultTableVC和favoriteTableVC视图控制器的初始化方法中放置断点,可以看到这一点。

- (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 allResult初始化
  • resultsTableVC init resultsTableVC初始化
  • allResults viewDidLoad allResults viewDidLoad
    • addSubview allResultsVC addSubview allResultsVC
    • addSubview favoritesResultsVC addSubview favoriteResultsVC
  • favoritesResultsVC init favoriteResultsVC初始化

This is a single thread, so I don't understand how viewDidLoad can be called before init is complete. 这是一个单线程,所以我不了解在初始化完成之前如何调用viewDidLoad。

-[ResultsTableVC initWithController:andTableView:] is probably referencing allResults.view. -[ResultsTableVC initWithController:andTableView:]可能引用了allResults.view。

This would force the allResults controller to load its view (which then of course causes viewDidLoad to fire). 这将迫使allResults控制器加载其视图(这当然会导致viewDidLoad触发)。 All of this happens synchronously, before you actually return from initWithController:andTableView: 所有这些都是同步发生的,实际上是您从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. 我的猜测是self.view当时指向nil
But that wouldn't explain why the init is call after... but no harm in trying. 但这并不能解释为什么init是在之后调用的,但是尝试时没有害处。
(I haven't tested it) (我还没有测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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