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 del
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
This one from NIMBUS would be more simple:
NSMutableArray* NICreateNonRetainingMutableArray(void) {
return (NSMutableArray *)CFArrayCreateMutable(nil, 0, nil);
}
NSMutableDictionary* NICreateNonRetainingMutableDictionary(void) {
return (NSMutableDictionary *)CFDictionaryCreateMutable(nil, 0, nil, nil);
}
NSMutableSet* NICreateNonRetainingMutableSet(void) {
return (NSMutableSet *)CFSetCreateMutable(nil, 0, nil);
}
Check documentation of NSValue valueWithNonretainedObject method :
This method is useful for preventing an object from being retained when it’s added to a collection object (such as an instance of NSArray or NSDictionary).
You do not want to do this! Cocoa Touch have several concepts for sending events, you should use the proper concept for each case.
What you should do is to look into how to use NSNotificationCenter
class. This is the proper way to send a notification that have more than one receiver.