How to get values of a specific key from an array of custom model objects
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).
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"];
Comments
-
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 over 10 yearsNSArray *areas = [[addresses valueForKey:@"area"] mutableCopy]; is this the way to use the mutablecopy. plese correct me if wrong