I would like to store a zeroing weak reference to an object in a NSDictionary
. This is for a reference to a parent NSDictionary
, so I can crawl back up a large structure without searching.
I can not use __weak
here; even if my local reference is weak, the NSDictionary
will store a strong reference to the object that was weakly referenced. And, of course, NSDictionary
can't have nil
objects.
I'm on iOS, not Mac, so NSHashTable
isn't available. And I only want one object to be weak; the rest should still be strong.
(I'm going to post my answer, so I have something to mark as accepted if there's no better answer. But I'm hoping someone has a better answer.)
An NSDictionary will retain it's objects, and copy it's keys.
An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.
NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.
In iOS 6+ you can use NSMapTable and choose if you want objects and/or keys to be weak or strong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With