Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Update:

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];
like image 338
David Avatar asked Mar 30 '12 13:03

David


2 Answers

Using a NSNumber is overkill. You can save yourself a lot of overhead by doing the following:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
    return (NSComparisonResult) [obj1 intValue] - [obj2 intValue];
}];
like image 55
Richard J. Ross III Avatar answered Oct 14 '22 14:10

Richard J. Ross III


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];
}];
like image 21
bandejapaisa Avatar answered Oct 14 '22 14:10

bandejapaisa