How do I sort an array of dictionaries using a given key?

I need to sort an array of dictionaries based on a given key. I tried the follow line of code:

set sortedTeams to theTeamsArray's sortedArrayUsingDescriptors_(theTeamsArray's initWithKey_Ascending_("rating", true))

and got the following errors:

2012-09-01 09:56:52.963 NFL Spreads Generator[12813:1307] -[__NSArrayM initWithKey:Ascending:]: unrecognized selector sent to instance 0x40012a8a0
2012-09-01 09:56:52.972 NFL Spreads Generator[12813:1307] *** -[NFL_Spreads_GeneratorAppDelegate generateTeamRatings:]: -[__NSArrayM initWithKey:Ascending:]: unrecognized selector sent to instance 0x40012a8a0 (error -10000)

“rating” is one of the keys in the dictionaries within theTeamsArray. The “init” in initWithKey:Ascending: is most likely a clue and I’m not sure how to follow it.

Hopefully I’m on the right path and just misstepped somewhere along the way.

Thanks in advance,
Brad

You have a couple of problems here. First, note that the method, sortedArrayUsingDescriptors: is plural – that’s a sure sign that the argument needs to be an array. So you need to give it an array of NSSortDescriptor objects, even if that array only contains one item. Second, you can never have an init method without an alloc, or in this case you can use the convenience method sortDescriptorWithKey:ascending: if you prefer.

set sorter to current application's NSSortDescriptor's sortDescriptorWithKey_ascending_("rating",true)
		set sorters to current application's NSArray's arrayWithObject_(sorter)
        set sortedTeams to theTeamsArray's sortedArrayUsingDescriptors_(sorters)

Ric

Thanks Ric, that’s exactly what I needed.