Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 679
Jeff Avatar asked Apr 20 '10 04:04

Jeff


People also ask

Does binary search need to be sorted?

Answer. In Binary Search, the array is repeatedly divided into two halves and the element is searched in that half whose last element is greater than or equal to the element being searched. For this reason, Binary Search needs a sorted array to perform the search operation.

Is it faster to iterate through an NSArray or an NSSet?

Yes, NSArray is faster than NSSet for simply holding and iterating. As little as 50% faster for constructing and as much as 500% faster for iterating.


2 Answers

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.

like image 70
Ian Henry Avatar answered Sep 29 '22 14:09

Ian Henry


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]; 
like image 36
Jesse Anderson Avatar answered Sep 29 '22 13:09

Jesse Anderson