Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSSets of a core data entity - Objective-C

I would like to sort the data of a core data NSSet (I know we can do it only with arrays but let me explain...). I have an entity user who has a relationship to-many with the entity recipe. A recipe has the attributes name and id. I would like to get the data such that:

NSArray *id = [[user.recipes valueForKey:@"identity"] allObjects];
NSArray *name = [[user.recipes valueForKey:@"name"] allObjects];

if I take the object at index 1 in both arrays, they correspond to the same recipe...

Thanks

like image 281
ncohen Avatar asked Mar 11 '10 17:03

ncohen


1 Answers

You need to sort the recipes first:

NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];

NSArray *sortedRecipes = [[recipes allObjects] sortedArrayUsingDescriptors:sortDescriptors];

you can then extract an array of attributes from the sorted recipes array and the results will remain in sorted order:

NSArray *sortedNames = [sortedRecipes valueForKey:@"name"];
NSArray *sortedIdentities = [sortedRecipes valueForKey:@"identity"];
like image 154
Barry Wark Avatar answered Sep 18 '22 18:09

Barry Wark