我有 NSFetchedResultsController
,它返回具有 index
属性的对象,index
属性是一个 NSString
,例如我index
属性具有以下值:-1、-3、1、0、-2、3
我需要定义 NSSortDescriptor,它将根据 index
属性值对这些对象进行排序:
-3, -2, -1, 0, 1, 3
我现在拥有的排序描述符无法正确排序负值。
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:ObjectIndex ascending:YES selector:@selector(localizedStandardCompare:)];
最佳答案
根据Apple Docs CoreData 的 SQLite 后备存储仅支持少数排序选择器:
... The SQL store, on the other hand, compiles the predicate and sort descriptors to SQL and evaluates the result in the database itself. This is done primarily for performance, but it means that evaluation happens in a non-Cocoa environment, and so sort descriptors (or predicates) that rely on Cocoa cannot work. The supported sort selectors are compare: and caseInsensitiveCompare:, localizedCompare:, localizedCaseInsensitiveCompare:, and localizedStandardCompare: (the latter is Finder-like sorting, and what most people should use most of the time).
(我的突出显示)。这些都无法实现您想要的。正如您所发现的,最后一个最接近:它将负数排在正数之前,并尝试数字排序(因此“23”排在“220”之前 - 文本排序会将它们倒过来)。但是(奇怪的是)负数是按照它们的绝对值排序的——所以“-1”出现在“-2”之前等等。果然,Finder 以相同的方式对负数进行排序。
所以我认为你最好的办法是重新设计你的数据库,使这个字段成为数字类型,这样你就可以使用合理的排序顺序。
关于ios - NSFetchedResultsController 对负字符串值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28938596/