NSArray from NSSet - Do I have to sort it myself?

Jeff picture Jeff · Apr 20, 2010 · Viewed 34.4k times · Source

I've got data in an NSSet, and I need to get it into an NSArray.

Do I need to sort it myself (again, this came from Core Data) or can I get it out in a sorted order?

Answer

Ian Henry picture Ian Henry · Apr 20, 2010

You can specify a sort when you retrieve data with an NSFetchRequest by setting the sortDescriptors property to an array of NSSortDescriptors. But if you already have it in an NSSet and don't want to make another fetch request, you can use:

[[theSet allObjects] sortedArrayUsingDescriptors:sortDescriptors];

It'll create an interim NSArray when you call allObjects and then another sorted array afterwards, so it's not 100% efficient, but the overhead should be negligible for reasonably-sized data sets (and certainly less than the cost of sorting).

Edit

Actually, I was wrong - NSSet has the sortedArrayUsingDescriptors: method too. So you can just call [theSet sortedArrayUsingDescriptors:descriptors] and do it all in one go.