2

I'm trying to get array of just specifying key's value in following array obj.

Ex1) If specifying key "name",
    wanted result is : {"James", "Jhone", "Michael", "Donald", "Mac"}

Ex2) If specifying key "age",
    wanted result is : {25,27,35,25,26}

How to get?

Please help or advise.

NSArray *array = [[[NSArray alloc] initWithObjects:
        @{@"name" : @"James", @"age" : @25},
                @{@"name" : @"Jhone", @"age" : @27},
                @{@"name" : @"Michael", @"age" : @35},
                @{@"name" : @"Donald", @"age" : @25},
                @{@"name" : @"Mac", @"age" : @26},
                nil] autorelease];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"???  == name"];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"result : %@", filtered);

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"???  == age"];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"result : %@", filtered);
1

2 Answers 2

11

Give this a try:

[array valueForKey:specifyingKey]

Hope this helps!

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

2 Comments

damn. I should have refreshed before hitting Post Your Answer. +1 to you for speed.
what if I want to have array with more than one keys?
2

Just use KVC.

[array valueForKey:@"age"]

should give you an array of the ages.

2 Comments

Umm.. I think there is no getValueForKey method. :D
lol. this is what happens when I reply to ObjectiveC stuff while I'm reading technical papers about other languages. Corrected.

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.