我正在尝试创建一个NSDictionary,它使用基于ID的键存储对象.我知道我可以使用NSNumber对象,但为什么我不能只使用int呢?是否有一些课程支持这个?像NSSet这样的东西几乎可以工作,除了我不能通过它的哈希值访问它(我已经重写- (NSUInteger) hash了返回对象的ID,它始终是唯一的)
我基本上试图改变这个:
//objects is an NSMutableDictionary
- (id) objectForId:(NSUInteger)id {
return [objects objectForKey:[NSNumber numberWithInt:id]];
}
- (void) addObject:(Object *)foo {
[objects setObject:foo forKey:[NSNumber numberWithInt:id]];
}
Run Code Online (Sandbox Code Playgroud)
进入这个:
//objects is an NSSet
- (id) objectForId:(NSUInteger)id {
return [objects objectForHash:id];
}
- (void) addObject:(Object *)foo {
[objects addObject:foo];
}
Run Code Online (Sandbox Code Playgroud)
bbu*_*bum 11
在配置NSMapTable实例以使用整数键之后,您将要使用C API到NSMapTable.一个例子:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMapTable *mt = [NSMapTable mapTableWithKeyOptions: NSPointerFunctionsIntegerPersonality | NSPointerFunctionsOpaqueMemory
valueOptions: NSPointerFunctionsObjectPersonality];
for(NSUInteger i = 0; i<10; i++)
NSMapInsert(mt, (void *) i, [NSNumber numberWithInt: i]);
for(NSUInteger j = 0; j<10; j++)
NSLog(@"retrieved %@", (id) NSMapGet(mt, (void *) j));
[pool drain];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,NSMapTable()中似乎存在一个错误,它不允许0成为键.哎呀.
在<rdar:// problem/7228605>中请求更好地记录NSMapTable的功能API.
<rdar:// problem/7228618>中记录了对0键问题的修复