7

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.

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

NSMutableArray *areas = [addresses mutableArrayValueForKey:@"name"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.