Sunday, April 22, 2012

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?



Source: Tips4all

2 comments:

  1. - (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
    {
    id objectInstance;
    NSUInteger indexKey = 0;

    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
    for (objectInstance in array)
    [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]]

    return (NSDictionary *)[mutableDictionary autorelease];
    }

    ReplyDelete
  2. 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;
    }

    ReplyDelete