NSSortDescriptor evaluating ascending numbers (Swift)

社会主义新天地 提交于 2019-12-01 16:48:24
Volker

The values you want to sort are actually strings and not numbers, thus the strange sort order. For Swift there exist an initializer init(key:ascending:selector:) of NSSortDescriptorand thus you can use selector: "localizedStandardCompare:" as described for example at nshipster.com/nssortdescriptor

The localizedStandardCompare: gives you a Finder like sorting of string values in a way that numbers are sorted naturally as you would sort numbers. So 1,...,9,10,...,99, 100 etc.

In my case I tried it with

let descriptor: NSSortDescriptor = NSSortDescriptor(key: "formId", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:))) Its working for me.

        let descriptor: NSSortDescriptor = NSSortDescriptor(key: "message_time", ascending: true)
        let sortedResults = arrayForMessages.sortedArray(using: [descriptor])
        print(sortedResults)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!