使用NSSortDescriptor对NSString值进行排序,如同NSInteger [英] Sorting NSString values as if NSInteger using NSSortDescriptor
本文介绍了使用NSSortDescriptor对NSString值进行排序,如同NSInteger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个排序描述符,对来自我的服务器的plist响应进行排序。这对于值为高达9的排序键很有效。对于超过10个项目,我看到排序键排序为1,10,11,2,3,4,5,6,7,8, / p>
I have created a sort descriptor to sort a plist response coming from my server. This works well with sort key having values upto 9. With more than 10 items I see abrupt results with sort key arranged in the order = 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sort" ascending:YES];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];
如何使其按照正确的顺序排列:1,2,3,4,5,6 ,7,8,9,10,11?
How to make it arrange in the correct order of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11?
推荐答案
您可以通过实现一个自定义比较器块来创建 NSSortDescriptor
:
You can do this by implementing a custom comparator block when creating your NSSortDescriptor
:
NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];
请参阅Apple文档在这里
See Apple documentation here
这篇关于使用NSSortDescriptor对NSString值进行排序,如同NSInteger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文