NSSortDescriptor evaluating ascending numbers (Swift)

The application has a contentid included in the number line from the json file:

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

Then it is saved in [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 return Core Data records in numerical order:

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

But records 6 - 10 are returned as: 10, 6, 7, 8, 9 . What will be the correct method for correctly calculating these numbers using NSSortDescriptor?

UPDATE:

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

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

and he rated the numbered lines as true integers.

UPDATE: Swift 2:

The selector syntax has changed and no longer accepts objc pointers. Thanks to user1828845.

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

+5
source share
3 answers

The values ​​you want to sort are actually strings, not numbers, thus a weird sort order. There is an init(key:ascending:selector:) initializer for Swift init(key:ascending:selector:) of NSSortDescriptor , and you can use selector: "localizedStandardCompare:" , as described, for example, in the file nshipster.com/nssortdescriptor

localizedStandardCompare: gives you a Finder, for example, sorting string values ​​so that numbers are sorted naturally, since you are sorting numbers. So, 1, ..., 9,10, ..., 99, 100, etc.

+3
source

In my case, I tried it with

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

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

All Articles