1

I have 4 values in my NSDictionary below which are 1000,640,80 and 0 It sorts the non-zero values correctly but it always gives 0 as greater than all the other values like (descending): 0,1000,640,80 Here's the code:

    NSMutableDictionary *dict = [[self model] stateFromDocumentNamed:@"state"];
    NSArray *values=[dict allValues];
    NSMutableArray *mutvalues = [(NSArray*)values mutableCopy];
    [mutvalues sortUsingSelector:@selector(compare:)];
    values=[[values reverseObjectEnumerator] allObjects];
    NSLog(@"%@",mutvalues);
2
  • 0 comes before 1. 0 < 1 < 6 < 8. You would get the same result if you used 0, 1, 6, 8 rather than 1000, 640, and 80. In which case they'd be in order. Commented Mar 11, 2014 at 23:39
  • are your values NSStrings ? Commented Mar 11, 2014 at 23:41

2 Answers 2

5

Presumably you are comparing strings which contain numbers. To have the sort work as you expect with the numbers you will want to use the NSNumericSearch option (in the method compare:options:, probably used with sortedArrayUsingComparator:).

Sign up to request clarification or add additional context in comments.

Comments

3

This is probably because the objects in your NSMutableDictionary are strings instead of numbers. Possible solutions:

  • You would need to convert all objects to numbers
  • Use a different selector to sort
  • sort using a block, using sortedArrayUsingComparator
  • EDIT: sort using method proposed in Wain's answer

Comments

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.