In a Cocoa Touch project, I need a specific class to have not only a single delegate object, but many of them.
It looks like I should create an NSArray for these delegates; the problem is that NSArray would have all these delegates retained, which it shouldn't (by convention objects should not retain their delegates).
Should I write my own array class to prevent retaining or are there simpler methods? Thank you!
Keyword:
NSHashTable
, search in documentations.I am presenting an important limitation of one of the earlier answers, along with an explanation and an improvement.
Johnmph suggested using
[NSValue valueWithNonretainedObject:]
.Note that when you do this, your reference acts not like
__weak
, but rather like__unsafe_unretained
while inside the NSValue object. More specifically, when you try to get your reference back (using [myNSValue nonretainedObjectValue]), your application will crash with an EXC_BAD_ACCESS signal if the object has been deallocated before that time!In other words, the weak reference is not automatically set to nil while inside the
NSValue
object. This took me a bunch of hours to figure out. I have worked around this by creating a simple class with only a weak ref property.More beautifully, by using
NSProxy
, we can treat the wrapper object entirely as if it is the contained object itself!Check documentation of NSValue valueWithNonretainedObject method :
I found some pieces of code from Three20 project about this topic, i hope this helps...
I'd suggest to not-fight-the-framework and use NSPointerArray with the
NSPointerFunctionsWeakMemory
NSPointerFunctionOption
like this:Served me well in scenarios, where I had to design a delegates array, which auto-NULL's references.
I found this bit of code awhile ago (can't remember who to attribute it to).
It's quite ingenius, using a Category to allow the creation of a mutable array that does no retain/release by backing it with a
CFArray
with proper callbacks.EDIT Found the original article: http://ofcodeandmen.poltras.com