Recently i've needed to implement the 'observer/notifier' pattern (is that what it's called?) in objective-c for an iphone app. The gist of this is that I need for my notifier to keep track of a set of observers.

However, due to the nature of reference counting (we're not garbage collected), this set of observers must hold weak references, and the observers' dealloc method must make a call to the notifier, telling it to remove the observer from the set. Without the weak reference, the observer will never be freed, and we have a memory leak.

Now the NSMutableSet always retains any object that it contains, so it's not much help. So here's my set that only holds weak references:

And here's an example of using it. The logged output from this test should all be 1's for the retain count:

[code] NSString *col = [NSString stringWithFormat:@"Blue"]; NSLog(@"Colour retain: %d", col.retainCount); WeakReferenceSet *set = [WeakReferenceSet set]; [set addObject:col]; NSLog(@"Colour retain: %d", col.retainCount); [set addObject:col]; [set addObject:col]; [set addObject:col]; NSLog(@"Colour retain: %d", col.retainCount); [set removeObject:col]; NSLog(@"Colour retain: %d", col.retainCount); [set removeObject:col]; [set removeObject:col]; [set removeObject:col]; NSLog(@"Colour retain: %d", col.retainCount); [set addObject:col]; NSLog(@"Colour retain: %d", col.retainCount); [set removeAllObjects]; NSLog(@"Colour retain: %d", col.retainCount); [/code]

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

Software Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!

Get in touch:
[email protected]
github.com/chrishulbert
linkedin



 Subscribe via RSS