NSFetchedResultsController 对负字符串值进行排序

NSFetchedResultsController sort negative string values

我有 NSFetchedResultsController 其中 returns 对象具有 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).

(我的突出显示)。 None 其中达到您想要的。正如您所发现的,最后一个最接近:它将负数排在正数之前,并尝试数字排序(因此“23”排在“220”之前 - 文本排序会将它们倒过来)。但是(奇怪的是)负数是按照它们的绝对值排序的——所以“-1”出现在“-2”之前等等。果然,Finder 以相同的方式对负数进行排序。

所以我认为你最好的办法是重新设计你的数据库,使这个字段成为数字类型,这样你就可以使用合理的排序顺序。