Search code examples
swiftswift2nsmanagedobjectnssortdescriptor

NSSortDescriptor and [__NSCFNumber localizedStandardCompare:]: unrecognized selector sent to instance


I am using sort descriptor to sort an array of an NSManagedObject (CoreData).

I have two sort descriptors for Int16 value (added the second one today).

For some reason, when trying to sort my array with the added descriptor, it crashes with:

[__NSCFNumber localizedStandardCompare:]: unrecognized selector sent to instance
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber localizedStandardCompare:]: unrecognized selector sent to instance

I even tried to change my data model (add an attribute as Int16 and populate it) but the app crashes every time I try to use the newly added descriptor.

The descriptor is very simple: let sortDescriptor4 = NSSortDescriptor(key: "the_int16_property", ascending: false, selector: "localizedStandardCompare:")

I am at a loss. Any advice would be helpful.

Thanks!


Solution

  • localizedStandardCompare: is a method of NSString to "compare strings as sorted by the Finder".

    Key-Value Coding for numerical Core Data properties (like "Int 16") uses NSNumber instances, and that class does not respond to localizedStandardCompare:.

    Just use the default compare: selector:

    NSSortDescriptor(key: "the_int16_property", ascending: false, selector: "compare:")
    // Swift 2.2 or later:
    NSSortDescriptor(key: "the_int16_property", ascending: false, selector: #selector(NSNumber.compare(_:)))
    

    or simply

    NSSortDescriptor(key: "the_int16_property", ascending: false)