Search code examples
iphoneobjective-ccocoa-touchnsarraynsdictionary

Convert NSMutableArray to NSDictionary in order to use objectForKey?


I have an NSMutableArray that looks like this

 {
    "@active" = false;
    "@name" = NAME1;
 },
 {
    "@active" = false;
    "@name" = NAME2;
 }

Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?


Solution

  • There is a even shorter form then this proposed by Hubert

    NSArray *allNames = [array valueForKey:@"name"];
    

    valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.

    From the docs:

    valueForKey:
    Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.

    - (id)valueForKey:(NSString *)key

    Parameters
    key The key to retrieve.

    Return Value
    The value of the retrieved key.

    Discussion
    The returned array contains NSNull elements for each object that returns nil.

    Example:

    NSArray *array = @[@{ @"active": @NO,@"name": @"Alice"},
                       @{ @"active": @NO,@"name": @"Bob"}];
    
    NSLog(@"%@\n%@", array, [array valueForKey:@"name"]);
    

    result:

    (
            {
            active = 0;
            name = Alice;
        },
            {
            active = 0;
            name = Bob;
        }
    )
    (
        Alice,
        Bob
    )