views:

68

answers:

2

In Objective-C I need to associate a mutable collection integers (monotonic, non-contiguous, could get fairly large) to boolean values. The obvious way is just to have an NSDictionary w/ NSNumbers as keys and values.

Is there a better way that doesn't involve so much object creation? I'm really not trying to pre-optimize so much as learn if there are techniques I'm not familiar with.

This data is private to a particular class implementation, so integrating with the rest of the Cocoa APIs isn't a requirement.

+2  A: 

Assuming you're happy with your integers being pointer-sized, you can use NSMapTable (also comes with a C API) or CFDictionary (which is toll-free bridged to NSDictionary).

Or, of course, you could use a (non-CF/Cocoa) C or C++ data structure, but it wouldn't integrate with Cocoa quite as cleanly.

Nicholas Riley
+1  A: 

The general case of mapping one scalar to another isn't something Cocoa handles that well, because it's focused on objects and scalars need to be wrapped before it has anything to offer. But in the case of booleans, there are only two possible mapped states, so that opens up a pretty handy way of doing it: NSIndexSet. Presence in the set = boolean state.

Chuck
...actually, that wasn't clear from the question: a mutable collection of integers to booleans has three states, true, false and absent.
Nicholas Riley
Oh, well, you could still stay pretty lightweight with one index set of true values and one of false values. Just wrap them in an interface that calls `removeIndex:` on one set when you add the index to the other.
Chuck
Good point. Another reason not to simply answer the question.
Nicholas Riley

related questions