我希望外面有人可以帮助我:
我有一个未排序的字典数组,其中有一个 STRING 字段 (Km),其中包含数字(例如 12,0;1,2;6,4)。如果我进行正常的排序,数组将以这种方式排序: 1,2 12,0 6,4
但它应该这样排序: 1,2 6,4 12,0
有人有如何执行此操作的示例代码吗? 我期待着得到答复。
感谢和问候 马可
编辑我的代码以进一步理解:
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]:发送到实例的无法识别的选择器
最佳答案
最好将数字作为 NSNumber 而不是字符串放入字典中。这避免了两个问题:
1 十进制数字的本地化,1.2 与 1,2 的工作方式会有所不同,具体取决于用户在世界上的位置。
2.数字的自然排序顺序是我们所期望的。
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 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7941357/