Convert NSArray to NSDictionary

后端 未结 6 1990
清酒与你
清酒与你 2020-12-02 22:13

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

6条回答
  •  再見小時候
    2020-12-02 23:09

    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;
    

提交回复
热议问题