Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak object in an NSDictionary?

Tags:

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

like image 791
Steven Fisher Avatar asked Jan 05 '12 19:01

Steven Fisher


People also ask

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.

What is a NSDictionary object?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.

What is the difference between NSMapTable vs NSDictionary?

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.


1 Answers

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

like image 52
João Nunes Avatar answered Oct 05 '22 21:10

João Nunes