views:

2170

answers:

2

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
Great solution Alex!
Jordan
+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 #imported 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
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