NSSortDescriptor evaluating ascending numbers (Swift)

一曲冷凌霜 提交于 2019-12-01 15:57:23

问题


App has contentid coming in as a number string from a json file:

let contentid: AnyObject! = jsonFeed["contentid"]

let stream:Dictionary = [
   "contentId": contentid as! String,
]

It is later saved to [NSManagedObject] with:

var articles = [NSManagedObject]()

let entity =  NSEntityDescription.entityForName("Article", inManagedObjectContext: managedContext)
let article = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

article.setValue(stream["contentId"], forKey: "contentid")

articles.append(article)

Finally, I use NSSortDescriptor to have Core Data return entries in numerical ascending order:

let sort = NSSortDescriptor(key: "contentid", ascending: true)
fetchRequest.sortDescriptors = [sort]

But entries 6 - 10 are returned as: 10, 6, 7, 8, 9. What would be the correct method of having these numbers evaluated correctly using NSSortDescriptor?

UPDATE:

For the Swift version, please see Volker's answer below. I ended up using:

let sort = NSSortDescriptor(key: "contentid", ascending: true, selector: "localizedStandardCompare:")

and it evaluated the numbered strings as true integers.

UPDATE: Swift 2:

Selector syntax has changed and no longer accepts objc pointers. Thank you user1828845.

let sort = NSSortDescriptor(key: "contentid", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))


回答1:


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.




回答2:


In my case I tried it with

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




回答3:


        let descriptor: NSSortDescriptor = NSSortDescriptor(key: "message_time", ascending: true)
        let sortedResults = arrayForMessages.sortedArray(using: [descriptor])
        print(sortedResults)


来源:https://stackoverflow.com/questions/30215508/nssortdescriptor-evaluating-ascending-numbers-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!