Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
johnl Avatar asked Sep 12 '09 10:09

johnl


People also ask

What is the difference between NSMapTable vs NSDictionary?

NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.

Can Nsarray contain nil?

arrays can't contain nil.

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

What is NSDictionary in Swift?

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).


2 Answers

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; 
like image 171
malhal Avatar answered Oct 09 '22 04:10

malhal


- (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]; } 
like image 28
Alex Reynolds Avatar answered Oct 09 '22 04:10

Alex Reynolds