iOS对数字字段排序NSMutableArray [英] IOS sort NSMutableArray for a numeric field

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

问题描述

我希望外面有人可以帮助我解决这个问题

I hope that there is somebody outside, who can help me with this:

我有一个未分类的字典数组,里面有一个STRING字段(Km),其中包含数字(例如12,0; 1,2; 6,4).如果我执行普通的SORT,则将以这种方式对数组进行排序: 1,2 12,0 6,4

I have an unsorted array of dictionaries which have a STRING field (Km) inside that contains numbers (e.g. 12,0; 1,2; 6,4). If I do a normal SORT, the array will be sorted that way: 1,2 12,0 6,4

但是应该这样排序: 1,2 6,4 12,0

But it should sorted that way: 1,2 6,4 12,0

有人有示例代码如何执行此操作吗? 我期待得到答案.

Does anybody has an example code how to do this? I'm looking forward to get an answer.

感谢和问候 马可

编辑代码以进一步了解:

Edit my code for further understanding:

NSMutableArray *tempArray = [[NSArray alloc] init];
self.Digger = tempArray;
[tempArray release];

self.Digger = [self.Diggers objectForKey:@"Rows"];

NSSortDescriptor * sort = [[[NSSortDescriptor alloc] initWithKey:@"KM" ascending:true] autorelease]; [self.Digger sortUsingDescriptors:[NSArray arrayWithObject:sort]];
self.Digger = sort;

但这给了我日志中的以下错误: -[NSSortDescriptor count]:无法识别的选择器已发送到实例

But this gives me the follwoing error in the log: -[NSSortDescriptor count]: unrecognized selector sent to instance

推荐答案

最好将数字作为NSNumbers而不是字符串放入字典中.这样可以避免两个问题:

It is best to put numbers into the dictionary as NSNumbers rather than strings. This avoids two problems:


1十进制数字(1.2对1,2)的本地化,其工作方式将因用户在世界上的位置而异.
2.想要的是数字的自然排序顺序.


1 The localization if decimal numbers, 1.2 vs 1,2 which will work differently depending un the user's location in the world.
2. The natural sort order of numbers is what is desired.

NSArray *a = [NSArray arrayWithObjects:
              [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:12.0] forKey:@"Km"],
              [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat: 1.2] forKey:@"Km"],
              [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat: 6.4] forKey:@"Km"],
              nil];

NSSortDescriptor * sort = [[[NSSortDescriptor alloc] initWithKey:@"Km" ascending:true] autorelease];
NSArray *sa = [a sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
NSLog(@"sa: %@", sa);

NSLog输出:

2011-10-30 10:08:58.791 TestNoARC[86602:f803] sa: (
                                                   {
                                                       Km = "1.2";
                                                   },
                                                   {
                                                       Km = "6.4";
                                                   },
                                                   {
                                                       Km = 12;
                                                   }
                                                   )

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

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