ioscore-datanssortdescriptor

Sort NSNumber with NSSortDescriptor


I have a Route as my top level Core Data entity. Then a Route has Locations. The Locations have a

@property (nonatomic, retain) NSNumber *index;

I need the index because I need to make sure the user's route is in order. I was wondering how I can best sort on the Locations entity. In my tableView, I show the name of the Route. Then when the user clicks on the Route, I show the Locations. I saw NSSet has

sortedArrayUsingDescriptors

but I wasn't aware of how I could sort NSNumber with a sortDescriptor. I have seen people just use code like

sortedArrayUsingSelector:@selector(compare:) // or something like that

I can write a simple convenience method to iterate through the NSSet and return the Location objects by their index, but wasn't sure if there was a better way. Thanks in advance!


Solution

  • Try using this as your sort descriptor:

    NSSortDescriptor* sort = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
    

    This will sort you location objects in ascending order by the value of their NSNumber* index property.