HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Simple yet efficient integer-to-object dictionaries?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simpleefficientyetdictionariesobjectinteger

Problem

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 >= 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  count) {
            NSUInteger delta = index - count;
            for (NSUInteger i=0; i<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.

Solution

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

Context

StackExchange Code Review Q#25321, answer score: 4

Revisions (0)

No revisions yet.