Is an NSMapTable
the same as an NSMutableDictionary
except for allowing keys to be pointers?
Does it differ in memory management?
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+
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 .
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
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+.
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