Simple yet efficient integer-to-object dictionaries? Sometimes I need an NSDictionary-like object that maps a few integers (non-negative) to objects. At first glance, NSMutableArray is great for this, provided that the indexes aren't too high so I came up with a quick category to allow holes in an array:

@implementation NSArray (FoundationAdditions)

-(id) objectAtCheckedIndex:(NSUInteger) index {
    if(index &gt;= self.count) {
        return nil;
    } else {
        id result =  [self objectAtIndex:index];
        return result == [NSNull null] ? nil : result;
    }
}

@end


@implementation NSMutableArray (FoundationAdditions)

-(void) setObject:(id) object atCheckedIndex:(NSUInteger) index {
    NSNull* null = [NSNull null];
    if (!object) {
        object = null;
    }

    NSUInteger count = self.count;
    if (index &lt; count) {
        [self replaceObjectAtIndex:index withObject:object];
    } else {
        if (index &gt; count) {
            NSUInteger delta = index - count;
            for (NSUInteger i=0; i&lt;delta;i++) {
                [self addObject:null];
            }
        }
        [self addObject:object];
    }
}

@end


Is there a better/easier/simpler way to do this? Preferably using something that's pre-existing in the Cocoa stack. Yes I know STL has some pretty good containers in this area, but mixing-in C++ just for this is overkill.
I would write a custom class that uses an NSMutableDictionary internally, boxing the indexes into NSNumber keys.

Depending on your particular use case it’s probably going to be both faster and more memory efficient than stuffing the unused array items with NSNull. Boxing the integer indexes into NSNumber key objects sounds like a lot of work performance-wise, but since the implementation uses tagged pointers, it should be pretty fast.

For extra points you can implement the object subscripting accessors (objectAtIndexedSubscript: and setObject:atIndexedSubscript:) and enjoy simple access syntax (foo[x]).