Convert NSArray to NSDictionary
Solution 1:
Try this magic:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:records
forKeys:[records valueForKey:@"intField"]];
FYI this is possible because of this built-in feature:
@interface NSArray(NSKeyValueCoding)
/* Return an array containing the results of invoking -valueForKey:
on each of the receiver's elements. The returned array will contain
NSNull elements for each instance of -valueForKey: returning nil.
*/
- (id)valueForKey:(NSString *)key;
Solution 2:
- (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];
}
Solution 3:
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;
}