Abolfoooud
Abolfoooud

Reputation: 2703

Filtering NSArray of NSDictionaries by all occurrence of particular key

I have been trying to get around this but so far without any success.

I know how to solve this using for loop but i want to learn it using NSPredicate

I have the following NSArray of NSDictionaries

[ { "content"="content1", "path"="/usr/name/..." },
  { "content"="acontent2", "path"="/usr/name/..." },
  { "content"="content3", "path"="/usr/name/..." },
  { "content"="content14", "path"="/usr/name/..." } ]

I want to return an array of all values of the "content" key for all items in the array. ie, the return should be

[ "content1", "content2", "content3", "content4" ]

How to do this?

Thanks

Upvotes: 0

Views: 108

Answers (2)

Wain
Wain

Reputation: 119031

Just use valueForKey:

NSArray *contentItems = [array valueForKey:@"content"];

Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
The returned array contains NSNull elements for each object that returns nil.

Upvotes: 2

Greg
Greg

Reputation: 25459

You can do it like that:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"content =[cd] %@", @"content1"];
NSArray * array = [YourArray filteredArrayUsingPredicate:pred];

This will filter your array to show all values where content = content1. But this is for filtering the array but the output you want:

[ "content1", "content2", "content3", "content4" ]

It looks more like sorting.

Hope I explained you how NSPredictate work.

Upvotes: 3

Related Questions