Is there something like NSSet that allows you to retrieve the hash value?

I am trying to create an NSDictionary that stores objects with ID-based keys. I know I can use NSNumber objects, but why can't I just use int instead? Is there any class out there that supports this? Something like NSSet almost works, except that I cannot access it with a hash value (I overridden - (NSUInteger) hash

to return an object id which is always unique)

Basically what I am trying to do is:

//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]];
}

      

in it:

//objects is an NSSet
- (id) objectForId:(NSUInteger)id {
  return [objects objectForHash:id];
}
- (void) addObject:(Object *)foo {
  [objects addObject:foo];
}

      

+2


source to share


3 answers


I ended up creating a category in NSDictionary to store objects based on int keys:



@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

      

+3


source


You will want to use the C API for the NSMapTable after setting up the NSMapTable instance to use integer keys. Example:

#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;
}

      

Note that there is a bug in NSMapTable () where it does not allow 0 to be a key. Unfortunately.



Better documentation of the functional API for NSMapTable is requested at <rdar: // issue / 7228605>.

The fix for key issue 0 is documented in <rdar: // issue / 7228618>

+11


source


NSDictionary

setObject:forKey:

already takes the key id

, which is similar to what you are doing with your NSSet

equivalent. What about NSDictionary is not enough for your purposes?

0


source







All Articles