David David - 1 year ago 134
iOS Question

NSSortDescriptor sort with number as string?

Got a an Array full of dictionary likes this:

{ order = "10";
name = "David"
{ order = "30";
name = "Jake";
{ order = "200";
name = "Michael";

When i'm using NSSortDescriptor like the code below it only sorts regarding to the first char so 200 is lower then 30. I can of course change the "order" object into a NSNumber instead of string and it would work. But is there a way to sort a string as int values without changing the source object?

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"norder" ascending:YES];
[departmentList sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];


Thanks to bandejapaisa.

Here is the a working version for iOS 5 (Xcode where compalining).

NSArray *sortedArray;
sortedArray = [departmentList sortedArrayUsingComparator:(NSComparator)^(id a, id b) {
NSNumber *num1 = [NSNumber numberWithInt:[[a objectForKey:@"norder"] intValue]];
NSNumber *num2 = [NSNumber numberWithInt:[[b objectForKey:@"norder"] intValue]];

return [num1 compare:num2];
departmentList = [sortedArray mutableCopy];

Answer Source

Maybe sort using a comparator instead, or one of the other sorting methods:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
  NSNumber *num1 = [NSNumber numberWithInt:[obj1 intValue]];
  NSNumber *num2 = [NSNumber numberWithInt:[obj2 intValue]];
  return (NSComparisonResult)[rank1 compare:num2];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download