The following code doesn't work:
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true, selector:"caseInsensitiveCompare")
And gives the following error:
'NSInvalidArgumentException', reason: 'unsupported NSSortDescriptor selector: caseInsensitiveCompare'
Seemed to work fine in Objective-C. Any ideas on why this might be?
Edit: seems like this may not be possible with Core Data/SQLite. In that case, is the best option to get the array and sort it in code afterwards?
The selector is caseInsensitiveCompare:
, with the colon, and you can use it with Core Data.
The colon is there because the method (which is an instance method of NSString
) takes one argument (the string to compare with).
As list of sort selectors which can be used with Core Data and a SQLite
store can be found in
Persistent Store Types and Behaviors in the Core Data Programming Guide.
Swift 3 - 5.0 Syntax
let sortDescriptor = NSSortDescriptor(key: "KeyName", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
Swift 5, SwiftUI syntax
self._contacts = FetchRequest(
entity: Contact.entity(),
sortDescriptors: [
NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
],
predicate: predicate
)