问题描述
我正在使用iOS应用程序,并且我将要存储在CoreData中的数据存储到UITableView中.数据实体具有名为 id
的属性,该属性是一个字符串,其中包含 A
后跟数字(即"A1","A2"等).
I am working on an iOS app and I have data stored in CoreData that I am loading into a UITableView. The data entities have an attribute called id
which is a string that contains an A
followed by a number (i.e. "A1" "A2" etc).
当我使用此代码进行排序时,最终将表按字典顺序进行排序(即"A1","A10","A11","A12","A2","A3"等)
When I use this code for sorting, I end up with the table being sorted lexicographically (i.e. "A1" "A10" "A11" "A12" "A2" "A3" etc)
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
我真正想要的是像您期望的那样对它进行数字排序.我该怎么做呢?我知道可以将 NSComparator
添加为 NSSortDescriptor
的参数,但是我一生都无法弄清楚.预先感谢您的帮助!
What I really want is for it to be sorted numerically, as you might expect. How do I go about doing this? I know that a NSComparator
can be added as an argument to NSSortDescriptor
but I can't for the life of me get it figured out. Thanks in advance for any help!
推荐答案
(基于SQLite的)Core Data提取请求中的排序描述符不能使用自定义比较器,仅使用有限的一组内置"比较方法.这记录在:
Fortunately, there is one that should fit your needs:
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true,
selector: "localizedStandardCompare:")
localizedStandardCompare:
进行类似Finder"的比较,特别是根据字符串中的数字数值.
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true
selector: #selector(NSString.localizedStandardCompare))
这篇关于Swift中的NSSortDescriptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!