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) {
[self replaceObjectAtIndex:index withObject:object];
} else {
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.
NSNumber
objects as keys if I useNSDictionary
for this use. – adib Apr 22 '13 at 5:10