Weak object in an NSDictionary?

Steven Fisher picture Steven Fisher · Jan 5, 2012 · Viewed 10.7k times · Source

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

Answer

João Nunes picture João Nunes · Feb 1, 2013

In iOS 6+ you can use NSMapTable and choose if you want objects and/or keys to be weak or strong.