15

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Gaurav Sharma
  • 2,680
  • 3
  • 26
  • 36

3 Answers3

52

Swift 3 - 5.0 Syntax

let sortDescriptor = NSSortDescriptor(key: "KeyName", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
AD Progress
  • 4,190
  • 1
  • 14
  • 33
gowthaman-mallow
  • 692
  • 1
  • 6
  • 10
14

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
8

Swift 5, SwiftUI syntax

self._contacts = FetchRequest(
            entity: Contact.entity(),
            sortDescriptors: [
                NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
            ],
            predicate: predicate
        )
Michał Ziobro
  • 10,759
  • 11
  • 88
  • 143