simplexity simplexity - 4 months ago 27x
Swift Question

NSSortDescriptor evaluating ascending numbers (Swift)

App has

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


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?


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.


The values you want to sot 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

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.