【发布时间】:2020-05-06 09:19:19
【问题描述】:
我一直在处理一个获取请求,使用这里的答案似乎可以正常工作:https://stackoverflow.com/a/60723054/1254397
import CoreData
import SwiftUI
struct DynamicFetchView<T: NSManagedObject, Content: View>: View {
let fetchRequest: FetchRequest<T>
let content: (FetchedResults<T>) -> Content
var body: some View {
self.content(fetchRequest.wrappedValue)
}
init(predicate: NSPredicate?, fetchLimit:Int = 5, sortDescriptors: [NSSortDescriptor], @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) {
fetchRequest = FetchRequest<T>(entity: T.entity(), sortDescriptors: sortDescriptors, predicate: predicate, fetchLimit)
self.content = content
}
init(fetchRequest: NSFetchRequest<T>, @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) {
self.fetchRequest = FetchRequest<T>(fetchRequest: fetchRequest)
self.content = content
}
}
在我看来:
DynamicFetchView(predicate: NSPredicate(format: "Brand CONTAINS %@", "GAP"), sortDescriptors: [NSSortDescriptor(keyPath: \store.brandName, ascending: false)]) { (clothing: FetchedResults<Store>) in
HStack {
Text("Number of Gap products: \(clothing.count)")
.bold()
.underline()
List {
ForEach(clothing) { Store in
Text("Clothing Name: \(Store.clothingName!)")
}
}
}
DynamicFetchView 可以很好地显示 fetch 请求中的所有内容,但我想将其限制为 5。我尝试添加 fetchLimit=5 但似乎没有任何区别。
【问题讨论】:
标签: swift core-data swiftui nsfetchrequest