Posterous theme by Cory Watilo

NSMutableSet with weak references in objective-c

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:



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);


| Viewed
times