How can I convert an NSArray to an NSDictionary, using an int field of the array's objects as key for the NSDictionary?
+12
A:
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
id objectInstance;
NSUInteger indexKey = 0;
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
for (objectInstance in array) {
[mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithInt:indexKey]]
indexKey++;
}
return (NSDictionary *)[mutableDictionary autorelease];
}
Alex Reynolds
2009-09-12 11:02:09
Great solution Alex!
Jordan
2009-09-12 13:45:55
+3
A:
This adds a category extension to NSArray
. Needs C99
mode (which is the default these days, but just in case).
In a .h
file somewhere that can be #import
ed by all..
@interface NSArray (indexKeyedDictionaryExtension)
- (NSDictionary *)indexKeyedDictionary
@end
In a .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
Example use:
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
2009-09-12 12:49:29
I love using categories, so I'd preffer this solution instead of using a simple function because of the way of calling it directly on the object itself, as if it always knew that method.
Woofy
2009-09-19 12:10:05