Help us understand the problem. What is going on with this article?

UIViewControllerのview.windowがロードされるタイミング

More than 5 years have passed since last update.

UIViewController - viewDidLoadでself.view.windowを参照しようとしてハマったのでメモ。iOSは基本的に単一のUIWindowしか持っていないのだけど、UIView.windowで自身が所属するwindowを特定する場合、タイミングが重要な場合がある。例えば以下。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIWindow *vw = self.view.window;
    UIWindow *aw = [[[UIApplication sharedApplication] delegate] window];
    NSLog(@"view has window? : %@", (vw)); // ない
    NSLog(@"app has window? : %@", (aw)); // ある
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIWindow *vw = self.view.window;
    UIWindow *aw = [[[UIApplication sharedApplication] delegate] window];
    NSLog(@"view has window? : %@", vw); //ない
    NSLog(@"app has window? : %@",aw); //ある
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    UIWindow *vw = self.view.window;
    UIWindow *aw = [[[UIApplication sharedApplication] delegate] window];
    NSLog(@"view has window? : %@", vw); //ある
    NSLog(@"app has window? : %@",aw); //ある
}

UIViewControllerのviewがwindowに所属するのはviewWillApperar:とviewDidAppearの間らしい。ちなみにその時のvwとawは同じオブジェクト。なので、何らかの理由でviewDidLoadでwindowの情報が欲しかったらapplicationDelegate.windowを使いましょう。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away