Objective c 是否有类似NSSet的东西允许通过哈希值进行检索?
我正在尝试创建一个NSDictionary,它存储具有基于ID的键的对象。我知道我可以使用NSNumber对象,但是为什么我不能用int来代替呢?是否有支持此功能的类?类似NSSet的东西几乎可以工作,除了我不能通过它的散列值访问它(我已经覆盖了Objective c 是否有类似NSSet的东西允许通过哈希值进行检索?,objective-c,Objective C,我正在尝试创建一个NSDictionary,它存储具有基于ID的键的对象。我知道我可以使用NSNumber对象,但是为什么我不能用int来代替呢?是否有支持此功能的类?类似NSSet的东西几乎可以工作,除了我不能通过它的散列值访问它(我已经覆盖了-(NSUInteger)散列,以返回对象的ID,它总是唯一的) 我基本上是想扭转这种局面: //objects is an NSMutableDictionary - (id) objectForId:(NSUInteger)id { return
-(NSUInteger)散列
,以返回对象的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]];
}
为此:
//objects is an NSSet
- (id) objectForId:(NSUInteger)id {
return [objects objectForHash:id];
}
- (void) addObject:(Object *)foo {
[objects addObject:foo];
}
NSDictionary
已经通过id
获取了密钥,这看起来就像您正在使用NSSet
等效项所做的一样。NSMapTable实例配置为使用整数键后,您需要使用NSMapTable的C API。例如:
#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;
}
#导入
int main(int argc,const char*argv[]{
NSAutoreleasePool*池=[[NSAutoreleasePool alloc]init];
NSMapTable*mt=[NSMapTable MAPTABLE WITHKEYOPTIONS:NSPointerFunctionsIntegerPersonality | NSPointerFunctionsPaqueMemory
值选项:NSPointerFunctionsObjectPersonal];
对于(i=0;i整数),我在NSDictionary上创建了一个类别来存储基于int键的对象:
@implementation NSMutableDictionary (IntKeyDictionary)
- (void) setObject:(id)obj forId:(int)id {
[self setObject:obj forKey:[NSNumber numberWithInt:id]];
}
- (void) removeObjectForId:(int)id {
[self removeObjectForKey:[NSNumber numberWithInt:id]];
}
- (id) objectForId:(int)id {
return [self objectForKey:[NSNumber numberWithInt:id]];
}
@end
这个类存在于iPhone API中吗?不幸的是,它不存在。但我相信你可以使用CFDictionary(非常确定——但还没有完成思考练习,可以说100%确定)。