Swift DynamicFetchView的fetchlimit。

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

我一直在做一个fetch请求,使用这里的答案似乎可以正常工作。https:/stackoverflow.coma607230541254397

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 我试过添加fetchLimit=5,但似乎没有任何区别。

swift core-data swiftui nsfetchrequest
1个回答
0
投票

这里有一个解决方案。

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) {
        guard let entityName = T.entity().name else { fatalError("Unknown entity") }

        let request = NSFetchRequest<T>(entityName: entityName)
        request.fetchLimit = fetchLimit
        request.sortDescriptors = sortDescriptors
        request.predicate = predicate

        self.init(fetchRequest: request, content: content)
    }

    init(fetchRequest: NSFetchRequest<T>, @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) {
        self.fetchRequest = FetchRequest<T>(fetchRequest: fetchRequest)
        self.content = content
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.