Convert NSArray to NSDictionary

后端 未结 6 2000
清酒与你
清酒与你 2020-12-02 22:13

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

6条回答
  •  难免孤独
    2020-12-02 22:53

    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;
    }
    

提交回复
热议问题