0

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];

4
  • If you have a property -(NSString*)distance in addition to ivar distance, your trick should just work. Commented Jun 27, 2012 at 15:12
  • @HotLicks it makes the array only have one object 10000 times. and dasblinkenlight its a NSNumber Commented Jun 27, 2012 at 15:14
  • 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/…) Commented Jun 27, 2012 at 15:17
  • yes of course, @tarheel. Commented Jun 27, 2012 at 15:18

1 Answer 1

1

This is what I use:

NSSortDescriptor *lowToHigh = [[NSSortDescriptor alloc] initWithKey:@"distance"
                                              ascending:YES];
NSArray *mySortDescriptors = [NSArray arrayWithObject:lowToHigh];
NSArray *sortedArray = [locationArray sortedArrayUsingDescriptors:mySortDescriptors];
Sign up to request clarification or add additional context in comments.

12 Comments

The only difference between what I tried and what you posted is the sortedArrayUsingDescriptors vs sortUsingDescriptors. Which unfortunately gives me the same exact sorting as I did before posting this question.
Sorry I was primarily referring to alloc/initing them, but I now see the comment asking about it. Besides that they are the exact same.
I think my issue is I don't have a key called distance only an NSNumber called distance.
@JohnRiselvato -- You mean you never defined the @property called distance, I suspect.
Look at this, I think he is trying to do almost the exact same thing except with an NSDate: stackoverflow.com/questions/805547/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.