Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Fire and forget" class in ARC

I needed to make a custom UIAlertView for my app, and I came across this article describing how to do it. I have since made a few changes to it, but the more important fact remains that this class does not function as a "Fire and forget" alert, the way that UIAlertView does, because ARC does not allow one to call retain.

So basically, I want to be able to utilize my custom alert view the same way as a normal alert view, so I can create and display one like this:

CustomAlertView *alert = [[CustomAlertView alloc] init];//Init presumably does the view setup
[alert show];

So my question is, how can I get this object not to deallocate as soon as it goes out of scope when working in an ARC project, without creating a strong reference to it in the calling class?

EDIT

I suppose it is important to mention, that in order to get the full freedom of view customizability I wanted, I had to make this a new ViewController class, it is NOT a subclass of UIAlertView

EDIT 2

I'm sorry, I didn't look at my link too closely, I had the wrong tutorial linked originally. THIS is the correct tutorial I based my view off of

like image 975
Dan F Avatar asked Nov 14 '22 02:11

Dan F


1 Answers

If you want to mimic the way UIAlertView works, you need to create a new UIWindow object, initialize it properly and show it using [window makeKeyAndVisible]. Beware that this will present, but not retain the window. If the reference count of the window drops to zero, the window is removed from the screen.

You want to deliberately create a retain cycle, which you break once your alertview is dismissed.

I.e. your customalertview class creates and retains a UIWindow, and the UIWindow retains its subview: your customalertview class. Then, by releasing the UIWindow, the window will release your customalertview.

like image 133
mvds Avatar answered Dec 21 '22 04:12

mvds