Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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?
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
ReplyDelete{
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];
}
This adds a category extension to NSArray. Needs C99 mode (which is the default these days, but just in case).
ReplyDeleteIn 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;
}