对许多包含数字的 NSArray 进行排序
我有一个 NSArray,其中填充了 NSMutableArray 中的对象。这些对象大多数都有整数值,如“1”、“2”、“3”、“4”、“5”,有时有一个名称,如“home”、“far left”或“far right”。我正在尝试在 Objective C 中对这个数组进行排序。当数组中的项目少于 10 个时,使用sortedArrayUsingSelector:@selector(compare:) 效果很好。但当有更多时,我开始得到“1”、“10”、“11”、“12”、“2”、“3”类型的东西。任何帮助将不胜感激。该代码不应返回任何内容。它只需要排序并继续前进。
原始代码:
presetNamesSort = [[[NSMutableArray alloc]init]retain];
presetNamesSort = [presetNames sortedArrayUsingSelector:@selector(compare:)];
I have an NSArray which is populated with objects from an NSMutableArray. Most of these object have integer values like "1", "2", "3", "4", "5", sometimes there is a name like "home", "far left", or "far right". I am trying to sort this array in Objective C. using sortedArrayUsingSelector:@selector(compare:) works fine when I have less then 10 items in the array. but when it there are more I start getting "1", "10", "11", "12", "2", "3" type of stuff. Any help would be most appreciated. The code should not return anything. It just needs to sort and move on.
Original Code:
presetNamesSort = [[[NSMutableArray alloc]init]retain];
presetNamesSort = [presetNames sortedArrayUsingSelector:@selector(compare:)];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用于降序排序
和升序排序
For sorting Descending
And for asending
您可以使用
NSArray
的-sortedArrayUsingComparator:
方法通过自定义块获取排序数组。我发现这比-sortedArrayUsingSelector:
更方便,因为您可以内联声明比较器,如下所示:这将返回一个如下所示的数组:
一般来说,使用块非常好,因为它们消除了需要创建在代码中运行 amuk 的随机选择器。
You can use
NSArray
's-sortedArrayUsingComparator:
method to get a sorted array using a custom block. I find this more convenient than-sortedArrayUsingSelector:
, because you can declare the comparator inline, like so:This will return an array that looks like so:
In general, it's pretty nice to use blocks because they eliminate the need to create random selectors that run amuk in your code.
尝试将
-[NSString Compare:options:]
与NSNumericSearch
结合使用。要将其与-sortedArrayUsingSelector:
一起使用,您必须将比较调用包装到NSString
上的单独类别方法中:try using
-[NSString compare:options:]
withNSNumericSearch
. To use that with-sortedArrayUsingSelector:
you have to wrap the compare call into a separate category method onNSString
: