Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 254
vamsi575kg Avatar asked Sep 03 '13 09:09

vamsi575kg


People also ask

How do you access data from an array of objects?

You can access a nested array of objects either using dot notation or bracket notation. JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of an object. Both arrays and objects expose a key -> value structure.


2 Answers

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.

like image 104
trojanfoe Avatar answered Nov 02 '22 14:11

trojanfoe


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

NSMutableArray *areas = [addresses mutableArrayValueForKey:@"name"];
like image 28
MobileDev Avatar answered Nov 02 '22 16:11

MobileDev