开发者

hash table in objective-c

What cl开发者_运维技巧ass can I use to associate an index in a NSMutableIndexSet to an object?


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

There is also NSHashTable.


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)


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:].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜