How can I implement a class/object that has a reference to a bunch of non-retained id objects?
I want something similar to what UIControl/NSControl has: addTarget:(id)target action:(SEL)action ...; (in my case, though, I don’t need the UIControlEvents part). I want to use this target/action pattern (and preferably stay away from the delegate pattern) but for that I need to make sure the targets added to my object are not retained or retain cycles might happen.
I think implementing my own array using malloc/free to make sure targets are not retained would be one solution, but all this hassle smells like there is already a solution implemented somewhere. Is there?
On OS X you can create an
NSPointerArraythat will keep weak references to its objects with+[NSPointerArray weakObjectsPointerArray], or (if you want a dictionary) anNSMapTablewhich allows either or both of the keys and values to be held weakly.Neither of those are available currently on iOS, but Core Foundation is. On either OS X or iOS you can use
CFArrayorCFDictionary, passingNULLfor the callbacks to make the collection do no memory management of its contained objects. Be warned that if you try to use these as if they were their toll-free bridged Cocoa counterparts, the collection will not honor your non-retaining/non-copying desire. You’ll have to use the CF functions to interact with them (or whip up a wrapper class).You can also wrap your objects in
NSValues, usingvalueWithNonretainedObject:, and put those into a Cocoa collection (NSDictionary/NSarray). The collection will own the value, but the value will not own its object.