Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSortDescriptor evaluating ascending numbers (Swift)

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(_:)))

like image 792
simplexity Avatar asked May 13 '15 12:05

simplexity


2 Answers

In my case I tried it with

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

like image 133
user1828845 Avatar answered Nov 10 '22 18:11

user1828845


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.

like image 4
Volker Avatar answered Nov 10 '22 19:11

Volker