Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWindow's makeKeyAndVisible not playing nice with ARC

I'm recreating some kind of UIAlertView specific to my app, so I'm subclassing UIWindow to do it. The window gets added to [UIApplication sharedApplication].windows, but is never actually shown. I trimmed it down to this small piece of code:

UIWindow *testWindow = [[UIWindow alloc] initWithFrame:self.view.bounds];
testWindow.backgroundColor = [UIColor blueColor];
[testWindow makeKeyAndVisible];

When I log [UIApplication sharedApplication].windows, I see:

"<UIWindow: 0x83774f0; frame = (0 0; 320 480); opaque = NO; autoresize = RM+BM; layer = <UIWindowLayer: 0x8377660>>",
"<UIWindow: 0x8382630; frame = (0 0; 300 400); layer = <UIWindowLayer: 0xf573e60>>"

And yet that second window with a blue background color is nowehere to be seen.

UPDATE: this seems to be an issue only when ARC is enabled. I created 2 new "single view" projects, one with ARC enabled and the other with ARC disabled. Both are identical and I add the UIWindow code to viewDidAppear: of the main view controller. When I run the apps in the simulator, the blue window only shows up in the ARC-disabled project. It looks like ARC gets rid of my UIWindow too quickly and so it doesn't even have time to show up. Making it __strong didn't help. Still clueless...

like image 782
samvermette Avatar asked Dec 21 '22 04:12

samvermette


1 Answers

It looks like ARC gets rid of my UIWindow too quickly and so it doesn't even have time to show up. Making it __strong didn't help.

Making what __strong? The variable you showed in your question appears to be a local variable, which only exists until the method returns. When the method returns, the variable goes away, so nothing owns the window, so it will then get deallocated.

Assign the window's pointer to a __strong instance variable or a strong property. Then you'll have a longer-lasting ownership keeping the window alive. Set the ivar or property to nil after you dismiss the window.

As a side note, are you sure you want this to be a subclass of UIWindow and not UIView? Even UIAlertView is a view and not a window. If it creates its own window, you may want to do that—have the view create its own window as an implementation detail.

like image 115
Peter Hosey Avatar answered Jan 05 '23 07:01

Peter Hosey