How to get values of a specific key from an array of custom model objects

12,579

Solution 1

Well as long as the object is KVC-compliant for the area property then simply:

NSArray *areas = [addresses valueForKey:@"area"];

(If you want areas to be mutable, as per your code, then you'll need to use mutableCopy in the above statement).

See [NSArray valueForKey:]:

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

Solution 2

Also We are using mutableArrayValueForKey: method to get the array of values corresponding to the key

NSMutableArray *areas = [addresses mutableArrayValueForKey:@"name"];
Share:
12,579
vamsi575kg
Author by

vamsi575kg

in.linkedin.com/pub/vamsi-krishna/51/ab7/447/

Updated on June 12, 2022

Comments

  • vamsi575kg
    vamsi575kg almost 2 years

    I have an array of custom objects which contains a custom object Address with properties street, area, state, country.

    I need to get all the the names of the areas from that array so i did some thing like this.

    NSMutableArray *areas = [[NSMutableArray alloc]init];
        for (Address *item in addresses) {
            [areas addObject:item.area];
        }
    

    Now areas contain all the names of the area.

    Is there any other way to get the all the areas of address items with out looping through the array of addresses (as above), using predicates or some other way.

  • vamsi575kg
    vamsi575kg over 10 years
    NSArray *areas = [[addresses valueForKey:@"area"] mutableCopy]; is this the way to use the mutablecopy. plese correct me if wrong