Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSortDescriptor in Swift

Tags:

ios

swift

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).

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]

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!

like image 583
Christian Deiderich Avatar asked May 31 '15 04:05

Christian Deiderich


1 Answers

Swift 3

let sortDescriptor = NSSortDescriptor(key: "id", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare))

hope it helps

like image 98
Yu On Avatar answered Nov 09 '22 23:11

Yu On