Calling [self release]
is a big no-no because no object has information about what other object refer to it. The retention system is intended to make sure that if ObjA needs ObjB, that ObjB will remain in memory until ObjA no longer needs it. If ObjB releases itself, the entire system breaks down.
In this case, the UIAlert
itself retains the AlertUtility
object as it's delegate so you can release the AlertUtility
as soon as your done with it just as you would a UIAlert
.
So,this is fine:
AlertUtility *utility = [[AlertUtility alloc] init];
[utility displayAlert];
[utility release]; // released here, but still alive
It's not a problem if the AlertUtility
object is still alive past the release. A release doesn't necessarily kill an object. It merely says that the object sending the release message has no further need of the released object. Each retaining object just has the responsibility to balance all retains (including implicit ones like init
) with a release. Past that the retaining object has no interest and no responsibility for whether the system keeps released object alive or not.
After all, any single object may be retained by multiple retaining objects each with no knowledge of the other. In this case the AlertUtility
is retained once by the ViewController with init
. Then it is retained again by the UIAlert
as a delegate. (Edit: UIAlert assigns it delegate)When ViewController releases the AlertUtility
object, it will remain alive as long as the UIAlert
needs it and vice versa.
Since the UIAlert
object is retained by the UIWindow
when it is displayed this means that the AlertUtility
object will remain alive until after the UIAlert
is dismissed. (Edit: this is valid only for the view, not the AlertUtility delegate)
You would not normally have a UIAlert
delegate whose existence is solely dependent on that of the UIAlert
itself. Usually, the UIAlert
delegate is the view controller that evokes the alert. That way, you don't have to worry about the delegate dying before it completes the task associated with the alert.