Non-retaining array for delegates

wh1t3cat1k picture wh1t3cat1k · Jan 14, 2011 · Viewed 12.4k times · Source

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!

Answer

MarkPowell picture MarkPowell · Jan 14, 2011

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.

@implementation NSMutableArray (WeakReferences)
    + (id)mutableArrayUsingWeakReferences {
    return [self mutableArrayUsingWeakReferencesWithCapacity:0];
    }

    + (id)mutableArrayUsingWeakReferencesWithCapacity:(NSUInteger)capacity {
    CFArrayCallBacks callbacks = {0, NULL, NULL, CFCopyDescription, CFEqual};
    // We create a weak reference array
    return (id)(CFArrayCreateMutable(0, capacity, &callbacks));
    }
@end

EDIT Found the original article: http://ofcodeandmen.poltras.com