Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...