排序NSArray其中许多包含数字 [英] Sorting NSArray which many contain number

查看:184
本文介绍了排序NSArray其中许多包含数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSArray,其中填充了来自NSMuttableArray的对象。这些对象中的大多数具有诸如1,2,3,4,5的整数值,有时存在诸如home,far left或far right的名称。我试图在Objective C中排序这个数组。sortedArrayUsingSelector:@selector(compare :)工作正常,当我有少于10个项目在数组。但是当它有更多的我开始得到1,10,11,12,2,3类型的东西。任何帮助将最感激。代码不应返回任何内容。

I have an NSArray which is populated with objects from an NSMuttableArray. 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.

原始代码:

presetNamesSort = [[[NSMutableArray alloc]init]retain];

presetNamesSort = [presetNames sortedArrayUsingSelector:@selector(compare:)];


推荐答案

可以使用 NSArray ' -sortedArrayUsingComparator:方法使用自定义块获取排序数组。我发现这比 -sortedArrayUsingSelector:更方便,因为你可以声明比较器内联,如下:

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:

NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:NSNumericSearch];
}];

这将返回一个如下所示的数组:

This will return an array that looks like so:

(
    1,
    2,
    4,
    5,
    10,
    Hello,
    Hi
)

一般来说,消除在代码中创建运行amuk的随机选择器的需要。

In general, it's pretty nice to use blocks because they eliminate the need to create random selectors that run amuk in your code.

这篇关于排序NSArray其中许多包含数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆