NSSortDescriptor将数字排序为字符串? [英] 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";
};
)
当我像下面的代码一样使用NSSortDescriptor时,它只对第一个char进行排序,因此200低于30.我当然可以将order对象更改为NSNumber而不是字符串,它可以工作。但有没有办法将字符串排序为int值而不更改源对象?
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]];
更新:
感谢bandejapaisa。
Thanks to bandejapaisa.
这是适用于iOS 5的工作版本(Xcode,其中包括编译)。
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];
推荐答案
也许使用比较器排序,或者其中一个其他排序方法:
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];
}];
这篇关于NSSortDescriptor将数字排序为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!