Convert NSArray to NSDictionary

johnl picture johnl · Sep 12, 2009 · Viewed 63.3k times · Source

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

Answer

malhal picture malhal · Oct 17, 2013

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;