Getting unique items from NSMutableArray

Gidogeek picture Gidogeek · Jun 3, 2010 · Viewed 18.4k times · Source

I have a question about Objective-C today involving NSMutableArray. Coming from a .net/c# background I'm having some trouble working with these things.

Let's say I have an object called "Song"

My song has 3 properties:

  • Title
  • Artist
  • Genre

I have a NSMutableArray or NSArray which holds all my Song objects.

How would I go about trying to 'query' my array to get a new array with only (Unique) Artists or Genre's.

Where as in .net you would write a simple LINQ query with a DISTINCT clause, how would one solve this in Objective-C? I'm guessing with predicates but am struggling to find a solution.

Answer

Luke picture Luke · Jun 4, 2010

You could also use:

NSArray *uniqueArtists = [songs valueForKeyPath:@"@distinctUnionOfObjects.artist"];
NSArray *uniqueGenres = [songs valueForKeyPath:@"@distinctUnionOfObjects.genre"];

Likewise, if you need to compare the entire object you could create a new readonly property that combines the values you want to match on (via a hash or otherwise) dynamically and compare on that:

NSArray *array = [songs valueForKeyPath:@"@distinctUnionOfObjects.hash"];

NOTE: Keep in mind this returns the uniques values for the specified property, not the objects themselves. So it will be an array of NSString values, not Song values.