How can I convert an NSArray
to an NSDictionary
, using an int field of the array's objects as key for the 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.
arrays can't contain nil.
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).
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).
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;
- (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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With