问题
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?
回答1:
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.
回答2:
Swift 3 - 5.0 Syntax
let sortDescriptor = NSSortDescriptor(key: "KeyName", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
来源:https://stackoverflow.com/questions/35165986/case-insensitive-compare-with-core-data-and-swift