3

是否可以将 newsearable与 a 结合使用@FetchRequest

我有这样的代码:

struct FooListView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Foo.name, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Foo>

    @State var searchText = ""

    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    NavigationLink(destination: FooView(Foo: item)) {
                        Text(item.wrappedName)
                    }
                }
                .onDelete(perform: deleteItems)
            }
            .searchable(text: $searchText)
            .navigationTitle("Foos")
        }
    }
}

在这个简单的示例中,我想使用searchText来过滤我的FetchedResults.

4

2 回答 2

5

WWDC 2021 为 Swift 带来核心数据并发性,SwiftUI 在 21:33 左右就有一个很好的例子

https://developer.apple.com/wwdc21/10017

struct ContentView: View {
    @FetchRequest(sortDescriptors: [SortDescriptor(\Quake.time, order: .reverse)])
    private var quakes: FetchedResults<Quake>

    @State private var searchText = ""
    var query: Binding<String> {
        Binding {
            searchText
        } set: { newValue in
            searchText = newValue
            quakes.nsPredicate = newValue.isEmpty
                           ? nil
                           : NSPredicate(format: "place CONTAINS %@", newValue)
        }
    }

    var body: some View {
        List(quakes) { quake in
            QuakeRow(quake: quake)
        }
        .searchable(text: query)
    }
}
于 2021-07-27T17:55:21.303 回答
2

我不会使用额外的绑定使其过于复杂。为什么不仅仅在 searchText 上使用 onChange 修饰符。

struct ContentView: View {
    @FetchRequest(sortDescriptors: [SortDescriptor(\Quake.time, order: .reverse)])
    private var quakes: FetchedResults<Quake>
    
    @State private var searchText = ""
    
    var body: some View {
        List(quakes) { quake in
            QuakeRow(quake: quake)
        }
        .searchable(text: $searchText)
        .onChange(of: searchText) { newValue in
            quakes.nsPredicate = newValue.isEmpty ? nil : NSPredicate(format: "place CONTAINS %@", newValue)
        }
    }
}
于 2021-11-07T11:06:39.813 回答