当UserDefaults值更改SwiftUI时,@FetchRequest谓词未更新



我很难弄清楚如何使SwiftUI@FetchRequest仅在存储在UserDefaults中的布尔值为true时才使用谓词。

问题是当showAvailable的值发生变化时,FetchedResults不会发生变化。目前,我必须重新启动应用程序才能看到基于showAvailable值的结果。

struct ContentView: View {
@AppStorage("showAvailable") private var showAvailable : Bool = false

@FetchRequest private var list: FetchedResults<Item>

init() {
@AppStorage("showAvailable") var showAvailable : Bool = false
_list = FetchRequest(
sortDescriptors: [],
predicate: showAvailable ? NSPredicate(format: "parent == nil") : nil,
animation: .default
)
}
var body: some View {
Button("Cancel") {
showAvailable.toggle()
}
}

我会在Button操作中用一个新的谓词更新获取请求,该更新应该会触发请求再次执行

struct ContentView: View {
@AppStorage("showAvailable") private var showAvailable : Bool = false
@FetchRequest(sortDescriptors: [], 
predicate: NSPredicate(value: true)
animation: .default)
private var list: FetchedResults<Item>
var body: some View {
Button("Cancel") {
showAvailable.toggle()
updatePredicate()
}
.onAppear {
updatePredicate()
}
}
private func updatePredicate() {
if showAvailable {
list.nspredicate = NSPredicate(format: "parent == nil")
} else {
list.nspredicate = NSPredicate(value: true)
}        
}
}

最新更新