Search code examples
iphoneobjective-cnsarraynsdictionary

Convert NSArray to NSDictionary


How can I convert an NSArray to an NSDictionary, using an int field of the array's objects as key for the NSDictionary?


Solution

  • - (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array 
    {
      id objectInstance;
      NSUInteger indexKey = 0U;
    
      NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
      for (objectInstance in array)
        [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];
    
      return (NSDictionary *)[mutableDictionary autorelease];
    }