Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMapTable and NSMutableDictionary differences

Is an NSMapTable the same as an NSMutableDictionary except for allowing keys to be pointers?

Does it differ in memory management?

like image 923
123hal321 Avatar asked Aug 01 '11 21:08

123hal321


People also ask

What is NSMapTable?

A collection similar to a dictionary, but with a broader range of available memory semantics. iOS 6.0+ iPadOS 6.0+ macOS 10.5+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys. Here are some effects this has had on code I've worked on. Sometimes you get the same object you put in, sometimes not. Immutable objects are optimized to return themselves as a copy .

What is NSDictionary in Swift?

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


1 Answers

NSMapTable is more flexible than NSDictionary. While NSDictionary keeps strong references for values and copies the keys, you can configure NSMapTable to have any of those behaviors independently for objects and values: strong, weak or copy (more behavior options exist).


A practical use case: an NSDictionary keeps a strong reference (retains) of the pointer of the value, but copies the key. This means a) the key instance must implement the NSCopying protocol and b) depending on the complexity of the class, copying might add an overhead. On the other hand, you can configure an NSMapTable to act like an NSDictionary that uses strong references for both the values and the keys, no copying or NSCopying protocol needed.

An object-to-object behavior could previously be emulated using an NSDictionary if all the keys were NSNumbers containing the memory address of the source object in the mapping (don't laugh, I've seen it done) but outside of this run-around, NSMapTable offers a true object-to-object mapping for the first time in a Cocoa collection class.

(From a great article covering NSMapTable when it was introduced.)

Let's look at the API. This will return an object that works much the same as an NSMutableDictionary:

[NSMapTable mapTableWithKeyOptions:NSMapTableCopyIn
                      valueOptions:NSMapTableStrongMemory]

This will return an object that works doesn't copy the keys:

[NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory
                      valueOptions:NSMapTableStrongMemory]

Note: It looks like the NSMapTable API has changed in recent SDKs, but this syntax seems to be compatible with all SDKs.

NSMapTable is available on OS X 10.5+ and iOS 6.0+.

like image 150
Steph Thirion Avatar answered Nov 12 '22 06:11

Steph Thirion