how to get my UIWindow using UIApplication?

user416445 picture user416445 · Sep 23, 2010 · Viewed 52.4k times · Source

I have only one window and I tried

UIWindow* mWindow = [[UIApplication sharedApplication] keyWindow];

but this returned nil.

I also tried:

UIWindow* mWindow = (UIWindow*)[[UIApplication sharedApplication].windows objectAtIndex:0];

But this raised an exception and the app closed, when I tried to print out

[[UIApplication sharedApplication].windows count]

It printed 0

Note: I am putting this in my only view controller's viewDidLoad method and this is completely a new iPad View Based Application so I changed nothing, just trying to get the window

Please help me to get this object

Answer

Phlibbo picture Phlibbo · Sep 23, 2010

If your main window is an outlet of your AppDelegate (which should be the case), you may simply use

MyAppDelegate* myDelegate = (((MyAppDelegate*) [UIApplication sharedApplication].delegate));
[myDelegate.window ...]