使用NSSortDescriptor对数字进行排序 [英] Sorting Number using NSSortDescriptor

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

问题描述

我又遇到了另一个问题,但很长一段时间后。



这次我有数据库(核心数据),属性为数字其中包含整数,如213879,123,4,345,56567等。



我需要按升序数字顺序获取数据喜欢按字母顺序订单。



我这样做的方式如下,

  fetchRequest.sortDescriptors = [NSArray arrayWithObject:
[NSSortDescriptor sortDescriptorWithKey:@numbers
升序:YES
选择器:@selector (比较:)]];

但不幸的是它只比较了每个数字的第一位数,意味着如果有2个数字,如 123 321 ,它将比较 1(第一个数字的第一个数字) 3(第二个数字的第一个数字)并对它们进行排序。



当出现时它变得混乱 123 111 (所有数字的首位数相同)。



<如果我做错了或者SortDescriptor以这种方式工作?
我需要解决方案来同样按升序 123,133,213,451,516 对数字进行排序。



要记住的事情
实际上属性数字将包含整数数字超过6的数字。例如 1234567,234568,235481



感谢所有帮助我的人预期。

解决方案

您的属性似乎是 NSString 类型。确保你进入 NSNumber ,然后排序将按预期工作。



您的排序描述符中不需要选择器:@selector(compare:),因为这是默认值无论如何。


I got stuck in another problem again but after a long time.

This time I have database (Core Data), having an attribute of numbers which contains integer numbers like 213879,123,4,345,56567 and so.

I need to fetch data in ascending number order similar to like alphabetically order.

I am doing this in way given below,

fetchRequest.sortDescriptors=[NSArray arrayWithObject:
      [NSSortDescriptor sortDescriptorWithKey:@"numbers" 
                                    ascending:YES 
                                     selector:@selector(compare:)]];

but unfortunately it compares only the 1st digit of every number, mean if there are 2 numbers like 123 and 321, it will compare 1 (first digit of first number) with 3 (first digit of second number) and sort them.

It got confuse when there comes 123 and 111 (same first digits of all numbers).

If I am doing something wrong or the SortDescriptor works in this way? I need the solution to sort the numbers in ascending 123,133,213,451,516 likewise.

Thing to Remember In actual the attribute numbers will contains integer numbers having digits more then 6. e.g 1234567,234568,235481

Thanks to all who helps me a lot in anticipation.

解决方案

It seems your attribute is of type NSString. Make sure you make it to NSNumber, the sorting will then work as expected.

There is no need to selector:@selector(compare:) in your sort descriptor as this is the default anyway.

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

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