0
votes

I have a NSMutableArray of objects, below is the struct:

//object at index i
locations {
   NSString* address;
   NSString* state;
   NSNumber* distance;
}

I have 10000 object like the above structure in the NSMutableArray. How do order this array so that the locations are in order by the NSNumber distance?

I tried this:

lowToHigh = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
[locationArray sortUsingDescriptors:[NSArray arrayWithObject:lowToHigh]];

is using the sortDescriptorWithKey:@"distance" wrong? since distance isn't actually a key, it NSNumber* distance.

edit in my header @property (strong, nonatomic)NSNumber* _distance; and then @synthesize _distance = distance; in my methods file but this is in locationObjects.* object class. Then I import this in my current class I am doing this sorting. Is that an issue? How I import is locationObjects* locObj = [[locationObjects alloc] init];

1
If you have a property -(NSString*)distance in addition to ivar distance, your trick should just work. - Sergey Kalinichenko
@HotLicks it makes the array only have one object 10000 times. and dasblinkenlight its a NSNumber - John Riselvato
Did you alloc/init the actual lowToHigh NSSortDescriptor? (The 'Specifying Sorts Using NSSortDescriptor' section on this doc developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/…) - tarheel
yes of course, @tarheel. - John Riselvato

1 Answers

1
votes

This is what I use:

NSSortDescriptor *lowToHigh = [[NSSortDescriptor alloc] initWithKey:@"distance"
                                              ascending:YES];
NSArray *mySortDescriptors = [NSArray arrayWithObject:lowToHigh];
NSArray *sortedArray = [locationArray sortedArrayUsingDescriptors:mySortDescriptors];