How to get my UIWindow using UIApplication?

I have only one window and I tried

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

but it returned zero.

I also tried:

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

But this caused an exception and the application closed when I tried to print

 [[UIApplication sharedApplication].windows count] 

Printed 0

Note. I put this in my only viewDidLoad method of the view controller, and this is a completely new application for the iPad iPad, so I haven’t changed anything, just trying to get the window

Please help me get this object.

+41
iphone uiwindow uiapplication
Sep 23 '10 at 19:56
source share
4 answers

If your main window is the output of your AppDelegate (which should be so), you can simply use

 MyAppDelegate* myDelegate = (((MyAppDelegate*) [UIApplication sharedApplication].delegate)); [myDelegate.window ...] 
+47
Sep 23 '10 at 20:41
source share
β€” -

The easiest way is to get the window from the application delegate:

 UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window]; // Do something with the window now 
+32
Mar 25 '13 at 19:25
source share

Your application key is not set until <<20> is called into your application delegate. Your UIViewController is probably loading from the NIB before this call. This explains why keyWindow returns nil.

Fortunately, your view manager does not need to go through UIApplication to get a window. You can simply:

 UIWindow *mWindow = self.view.window; 
+19
Sep 23 '10 at 20:51
source share
 [[[UIApplication sharedApplication] windows] objectAtIndex:0]; // You can also check the count of this to make sure, because if there are no windows it will crash. 
+5
Aug 04 2018-11-11T00:
source share



All Articles