@Fetchrequest + Case-Insensitive Sorting - Swiftui & Coredata

@FetchRequest + case-insensitive sorting - SwiftUI & CoreData

You can pass NSString localizedStandardCompare method to the selector property:

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

How to prevent Core Data fetch request from resetting its predicate when SwiftUI List selection changes?

I tried your project and put in some breakpoints and the problem is when a selection is made, ContentView's body is called, which inits FruitPicker with the default FetchRequest instead of the one with the search predicate.

In looking over your coded I noticed some non-standard things. PersistenceController should be a struct not an ObservableObject (see the default app template with core data checked). The use of computed bindings looks odd to me but cool if it works.

To fix the problem you could break up the search and the list into 2 Views, so that the List is init with the new search term and then the FetchRequest will always be correct, e.g.

struct FruitPickerSearch: View {
@State var searchText = ""

var body: some View {
FruitPicker(searchText: searchText)
.searchable(text: $searchText)
.environment(\.editMode, .constant(EditMode.active))
.navigationTitle("Garden")
}
}

struct FruitPicker: View {
private var fetchRequest: FetchRequest<Fruit>
private var fruits: FetchedResults<Fruit> {
fetchRequest.wrappedValue
}

init(searchText: String){
let predicate = searchText.isEmpty ? nil : NSPredicate(format: "name CONTAINS[cd] %@", searchText)
fetchRequest = FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Fruit.name, ascending: true)],
predicate: predicate,
animation: .default)
}

var body: some View {
List(fruits) { fruit in
Text(fruit.name ?? "")
}
}
}

How to animate dynamic List sorting with SwiftUI and CoreData (@FetchRequest)

Binding can have attached animation, so try the following (or with any animation parameters you wish)

Picker("Sort by", selection: $currentSortMethod.animation())  // << here !!

COLLATE for Coredata created INDEX

No. If you'd like the ability to do so, please file an enhancement request. You get extra bonus points from the CoreData team if you can include a sample project showing how COLLATE would make things superbly and awesomely faster.



Related Topics



Leave a reply



Submit