11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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を使いましょう。

11
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?