I want to find the word with maximum characters of an entity attribute. I am trying to create a sort descriptor to compare string lengths. The code compiles, but I get the error unsupported NSSortDescriptor selector: comparatorOfStringLengths when the fetch query is executed. I tried the comparator block version of NSSortDescriptor but it is unsupported.
query.sortDescriptors = [
NSSortDescriptor.init(key: "word", ascending: false, selector: #selector(NSString.comparatorOfStringLengths))
]
Below is the latest version of the signature of the comparator method. I tried also using a static func with two arguments, and with Any instead of String as well, I get same result. I modeled this signature on the func localizedStandardCompare(_ string: String) -> ComparisonResult standard func.
extension NSString {
@objc func comparatorOfStringLengths(_ b: String) -> ComparisonResult {
if self.length < b.length {
return .orderedAscending
}
if self.length > b.length {
return .orderedDescending
}
return .orderedSame
}
}
EDIT: I adjusted/corrected the signature of selector specifier but this also fails:
#selector(NSString.comparatorOfStringLengths(_:)))

I could be wrong about that but i think with Core Data (iOS 13) such a
NSPredicateandNSSortDescriptoras you would like it is still not possible.An option might be to add an additional attribute
wordlenof number type that holds the length ofword. And fetch the entity with the highest value forwordlen.For further explanation i quickly switch to my Person standards example with the entity
Personwith a string attributename(corresponds towordin OP) and an integer attributenamelen.With the new function
validateNamelenthat will be placed where thePersoncode was generated:that will be triggered by Core Data and helps to synchronize the value of
namelenwith newly created or updatedPersonentities.Then adding an index
NameLenIndexonnamelenmakes the fetch faster:Swift 5 Code for evaluation:
Given an empty database at the beginning the output is like this: