views:

832

answers:

2

Hi everyone, 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

+2  A: 

If you want them to be in the same order, then you need to sort them before extracting the values. Example:

NSArray * sortedRecipes = [user.recipes sortedArrayUsingDescriptors:arrayOfSortDescriptors];
NSArray * identities = [sortedRecipes valueForKey:@"identity"];
NSArray * names = [sortedRecipes valueForKey:@"name"];

EDIT

My apologies. I just realized this is an iPhone question, and NSSet doesn't have sortedArrayUsingDescriptors: on the iPhone. However, it's trivial to work around:

NSArray * recipes = [user.recipes allObjects];
NSArray * sortedRecipes = [recipes sortedArrayUsingDescriptors:arrayOfSortDescriptors];
....
Dave DeLong
The problem is that user.recipes is an NSSet... so it won't work! And how do I sort the arrayOfSortDescriptors?thx
ncohen
+2  A: 

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"];
Barry Wark
Thanks this method works well... I just changed in the descriptor @"name" with @"id" and in the iPhone there is no instance method to create a descriptor so I changed the method sortDescriptorWithKey with initWithKey and released it!
ncohen