This adds a category extension to NSArray . Requires C99 mode (which is used by default these days, but just in case).
In the .h file somewhere that could be #import ed by everyone ..
@interface NSArray (indexKeyedDictionaryExtension) - (NSDictionary *)indexKeyedDictionary @end
In the .m .. file
@implementation NSArray (indexKeyedDictionaryExtension) - (NSDictionary *)indexKeyedDictionary { NSUInteger arrayCount = [self count]; id arrayObjects[arrayCount], objectKeys[arrayCount]; [self getObjects:arrayObjects range:NSMakeRange(0UL, arrayCount)]; for(NSUInteger index = 0UL; index < arrayCount; index++) { objectKeys[index] = [NSNumber numberWithUnsignedInteger:index]; } return([NSDictionary dictionaryWithObjects:arrayObjects forKeys:objectKeys count:arrayCount]); } @end
Usage example:
NSArray *array = [NSArray arrayWithObjects:@"zero", @"one", @"two", NULL]; NSDictionary *dictionary = [array indexKeyedDictionary]; NSLog(@"dictionary: %@", dictionary);
Outputs:
2009-09-12 08:41:53.128 test[66757:903] dictionary: { 0 = zero; 1 = one; 2 = two; }
johne Sep 12 '09 at 12:49 2009-09-12 12:49
source share