Take the 2-minute tour ×

I have an object that I have created that subscribes to some NSNotificationCenter notifications, but it is being released, since I don't have a pointer to the instantiation. The instantiation has a delegate that will call a method back to another class I have, so I felt it unnecessary to also have a pointer to it, since the pointer doesn't serve any purpose.

Basically, I have an instantiation of a class, DelegateListener (name is just for example purposes), which subscribes to some of the default NSNotificationCeneter's notifications. This instantiation isn't assigned to any pointer after the instantiation ends. The instantiation, however, has a property, delegate. I assign a value to that delegate during the instantiation. That delegate implements methods that I want the DelegateListener to call when the notifications that it subscribed to fire.

The problem with this is that the instantiation of DelegateListener that I create gets released, unless if I assign it to a retained pointer. Is there a way to avoid this automatic release of my DelegateListener instantiation within ARC?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

You should store the DelegateListener instance in a static variable if you don't have multiple of them.


The pointer does (or at least should) serve a purpose: when you no longer need to listen to the notifications, you should unsubscribe the DelegateListener from receiving them. At the very least, this should happen when your application goes to the background (unless the point of it is to perform background processing), and when your application terminates.

[[NSNotificationCenter defaultCenter] removeObserver:delegateListener];
share|improve this answer
I have the delegate returning to nil and I'm unsubscribing from the notifications upon dealloc. But you're saying that I should maintain my static pointer to it, since its the only way, huh. –  RileyE Sep 12 '12 at 4:03
Well, if it unsubscribes on dealloc then when ARC cleans it up it's going to unsubscribe then. So your delegate becomes useless. Keep a static pointer to it and then set the listener to nil when you want it to unsubscribe and your dealloc will take care of it as you say. –  darvids0n Sep 12 '12 at 4:06
@darvidsOn So, when there isn't a pointer, but it holds a delegate to a retained class, it will get released automatically? Isn't that annoying? –  RileyE Sep 12 '12 at 14:47
Unless the delegate retains its owner, that's very much standard behaviour. The runtime sees no object holding a reference to the delegate listener, so the assumption is made that no object will be able to reference anything at that memory address, and the memory is cleaned up. –  darvids0n Sep 13 '12 at 1:22
According to this answer, it doesn't hold a pointer. –  darvids0n Sep 13 '12 at 1:40
show 2 more comments

Your Answer


