Accessing value from array of objects

cocoa, cocoa-touch, foundation, ios, iphone

Solution

Assuming you started with an array like this:

NSArray *array1 = @[@{@name : @"Fred"},
                    @{@name : @"Bill"}];

You could create a second array that contains the value of a given property of each element of the first array as follows:

NSArray *array2 = [array1 valueForKey:@"name"];

If you then logged the second array...

NSLog(@"%@", array2);

...the resulting output would be

2012-04-18 16:26:11.226 ExampleRunner[23320:707] (
    Fred,
    Bill
)

EDIT

Note that this will work regardless of whether the objects in the first array are instances of `NSDictionary` as shown in the example above, or instances of a class or classes that have a `name` property or instance variable (or an `_name` instance variable, for that matter). For more information on how and why this works, see the documentation for the `NSKeyValueCoding` informal protocol:

http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/Reference/Reference.html

Problem

I am having two arrays, Namely ``` NMutableArray* first; NMutableArray* second; ``` Now I am copying first object to the second array like ``` for (int i=0;i<first.count; i++) { [second addObject:[first objectAtIndex:i]; } ``` This is ok. I don't know how to access the value of the First Array. I tried like this , ``` [second addObject:[[first objectAtIndex:i]name]]; ``` I want to get the name value which is in the first object of first array. I tried using the above line, it is showing some warning. Please help me

Original source