Sefran2
Sefran2

Reputation: 3588

hash table in objective-c

What class can I use to associate an index in a NSMutableIndexSet to an object?

Upvotes: 1

Views: 9957

Answers (3)

Dave DeLong
Dave DeLong

Reputation: 243166

If you want to use a raw integer as the key to an object, you can use a CFMutableDictionaryRef instead. This is going to drop you down a layer from Cocoa into CoreFoundation, but it'll still work just fine:

CFMutableDictionaryRef indexMap;

indexMap = CFDictionaryCreateMutable(NULL, 0, NULL, &kCFTypeDictionaryValueCallBacks);

NSUInteger key = 42;
id value = @"The Answer";
CFDictionarySetValue(indexMap, (const void *)key, value);

id value = CFDictionaryGetValue(indexMap, (const void *)key);
CFRelease(indexMap);

This is really handy if you're going to be accessing this dictionary frequently and don't want to deal with a whole bunch of transient NSNumber objects.

(I'm ignoring that you can toll-free bridge this, because once you start mucking around with the behaviors of keys and values, you don't really want to consider this an NSMutableDictionary at all)

Upvotes: 6

Barry Wark
Barry Wark

Reputation: 107774

You probably want to use an NS[Mutable]Dictionary. You can wrap the integer indexes in an NSNumber via -[NSNumber numberWithUnsignedInteger:] for the keys (this like manual boxing of primitives in Java) and add a key-value pair using -[NSMutableDictionary addObject:forKey:].

Upvotes: 2

user187676
user187676

Reputation:

NSDictionary or NSMutableDictionary. You can use objects as it's keys.

There is also NSHashTable.

Upvotes: 7

Related Questions