ios - NSSortDescriptor in Swift -
i working on ios app , have data stored in coredata loading uitableview. data entities have attribute called id string contains a followed number (i.e. "a1" "a2" etc).
when use code sorting, end table being sorted lexicographically (i.e. "a1" "a10" "a11" "a12" "a2" "a3" etc)
let sortdescriptor = nssortdescriptor(key: "id", ascending: true) fetchrequest.sortdescriptors = [sortdescriptor] what want sorted numerically, might expect. how go doing this? know nscomparator can added argument nssortdescriptor can't life of me figured out. in advance help!
sort descriptors in (sqlite-based) core data fetch request cannot use custom comparators , limited set of "built-in" comparison methods. documented in fetch predicates , sort descriptors in "core data programming guide":
... sql store, on other hand, compiles predicate , sort descriptors sql , evaluates result in database itself. done performance, means evaluation happens in non-cocoa environment, , sort descriptors (or predicates) rely on cocoa cannot work. supported sort selectors
compare:,caseinsensitivecompare:,localizedcompare:,localizedcaseinsensitivecompare:, ,localizedstandardcompare:(the latter finder-like sorting, , people should use of time). in addition cannot sort on transient properties using sqlite store.
fortunately, there 1 should fit needs:
let sortdescriptor = nssortdescriptor(key: "id", ascending: true, selector: "localizedstandardcompare:") localizedstandardcompare: "finder-like" comparison , in particular treats digits within strings according numerical value.
for swift 2.2/xcode 7.3 , later:
let sortdescriptor = nssortdescriptor(key: "id", ascending: true selector: #selector(nsstring.localizedstandardcompare))
Comments
Post a Comment