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



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?


Posted 2010-04-20T04:47:33.417

Reputation: 2 942

Part of the answer is that you can't get an NSArray out of a set in sorted order, so either you've got to sort it yourself, or when you get the MutableArray out of Core Data hang on to a copy once you build the set, so you can use that sorted copy where necessary. – Jeff – 2010-04-20T16:58:27.887



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).


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.

Ian Henry

Posted 2010-04-20T04:47:33.417

Reputation: 19 007

So with the descriptor : 'NSSortDescriptor sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray sortedArray = [theSet sortedArrayUsingDescriptors:@[sortDescriptor]];' – Numereyes – 2014-08-07T09:27:42.167


You've got to sort it yourself, but it's not very hard...

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Sprocket" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortVariable" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];   
[request setSortDescriptors:sortDescriptors];

NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    
self.sprocketArray = mutableFetchResults;

[sortDescriptors release];
[sortDescriptor release];
[mutableFetchResults release];
[request release];


Posted 2010-04-20T04:47:33.417

Reputation: 3 160

2you are saying that the OP would have to sort the data himself but you are providing a sample that is using CoreData's NSSortDecriptior functionality -- I would rephrase the answer and say; let CoreData do the sorting for you while fetching the data – Till – 2010-04-20T05:14:47.063

Good point. Thanks. – blindjesse – 2010-04-20T20:46:55.557