Search code examples
iosswiftcore-dataswiftuinsfetchrequest

@FetchRequest + case-insensitive sorting - SwiftUI & CoreData


I have a list of items being sorted by name.

I can create a fetch request which is case insensitive as follows:

struct ContentView: View {
   
   var fetchRequest: FetchRequest<Item>
   
   init() {
      fetchRequest = FetchRequest<Item>(entity: Item.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
      ])
   }
   
   var body: some View {
      // content
   }
   
}

Though I would prefer to do it like:

struct ContentView: View {
   
   @FetchRequest(entity: Item.entity(), sortDescriptors: [
      NSSortDescriptor(keyPath: \Item.name, ascending: true) // <-- can I add a selector here?
   ]) var items: FetchedResults<Item>
   
   var body: some View {
      // content
   }
   
}

Can @FetchRequest take a selector as an argument?

Going off the docs, NSSortDescriptor seems to take an argument called localizedCaseInsensitiveCompare, but I couldn't get it to work or find any examples online.


Solution

  • You can pass NSString localizedStandardCompare method to the selector property:

    NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.localizedStandardCompare))