Predicate 适用于 FetchedResults 但不适用于 FetchRequest

问题描述 投票:0回答:1

我想给 FetchRequest 添加一个谓词...

如果我将它放入 FetchRequest 中,它不起作用:

not working

@SectionedFetchRequest(sectionIdentifier: \Product.manufacturer?.name, 
                       sortDescriptors: [NSSortDescriptor(keyPath: \Product.name, ascending: true)], 
                       predicate: NSPredicate(format: "trashed = true")) // <-- not working

var products: SectionedFetchResults<String?, Product>

但是当我使用
.onChange

将它添加到FetchedResults时它正在工作

working

@SectionedFetchRequest(sectionIdentifier: \Product.manufacturer?.name, 
                       sortDescriptors: [NSSortDescriptor(keyPath: \Product.name, ascending: true)], 
                      // -- no predicate in FetchRequest --)

var products: SectionedFetchResults<String?, Product>

var body: some View {
    List {
        ForEach(products) { product in
            Text(product.name)
        }
        Button {
            testPred.toggle()
        } label: {
            Text("activate predicate")
        }
    }
}
.onChange(of: isSortedAscending) { _ in
    products.nsPredicate = NSPredicate(format: "trashed = true") // <-- working
}

edit 1

我现在唯一的想法是问这是否与这些设置有关?

publicDescription.cloudKitContainerOptions = options
publicDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
publicDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
swift swiftui core-data
1个回答
0
投票

我发现了问题,但我现在真的要发疯了!

谓词一直有效。
但是,我已将此代码附加到视图中:

.onReceive(tabaccoName.$debounced) { query in
            /// don't filter when searchbar is empty
            guard !query.isEmpty else {
                tabaccos.nsPredicate = nil // <-- PROBLEM
                return
            }
            
            /// set filter when someone searches
            tabaccos.nsPredicate = NSPredicate(format: "%K CONTAINS[cd] %@", argumentArray: [#keyPath(Tabacco.name), query])
        }

而这个每次都立即将谓词设置为

nil

© www.soinside.com 2019 - 2024. All rights reserved.