s_diaconu
s_diaconu

Reputation: 305

How to use SectionedFetchRequest in a view model?

I have a SwiftUI view that I want to move the fetch request in a view model. For normal fetching I did it like this

Consider this model

class MyType {
    let title: String
    let category: String

    init(title: String, category: String) {
        self.title = title
        self.category = category
    }
}

Then the view model

class MyTypeViewModel: ObservableObject {
    @Published var myTypes = [MyType]()
    private let context: NSManagedObjectContext

    init(context: NSManagedObjectContext) {
        self.context = context
        fetchMyTypes()
    }

    func fetchMyTypes() {
        let request = NSFetchRequest<MyType>(entityName: "MyType")
    
        do {
            myTypes = try context.fetch(request)
        } catch {
            print("DEBUG: Some error occured while fetching")
        }
    }
}

Is there a way to use property wrapper SectionedFetchResults in a view model?

On my swift ui view the request is used like this

struct FilteredSectionedListView: View {
    @Environment(\.managedObjectContext) private var context

    var myTypesRequest: SectionedFetchRequest<String?,MyType>
    var myTypes: SectionedFetchResults<String?,MyType>{myTypesRequest.wrappedValue}

    init(descriptor: [SortDescriptor<MyType>], filter: String, context: NSManagedObjectContext) {
    self.filter = filter
    myTypesRequest = SectionedFetchRequest<String?,MyType>(
        sectionIdentifier: \MyType.title!,
        sortDescriptors: descriptor,
        predicate: filter == "" ? nil : NSPredicate(format: "title CONTAINS[cd] %@", filter),
        animation: .default)
    }

    var body: some View {
        List {
            ForEach(myTypes) { section in
                Section(header: Text(section.id ?? "Unknown")) {
                    ForEach(section) { myType in
                        Text("\(myType.category!)")
                    }
                }
            }
        }
    }
}

Is the a sectioned equivalent for NSFetchRequest? Or sectioned fetch for NSManagedObjectContext?

Any help would appreciate it. Thanks!

Upvotes: 0

Views: 56

Answers (0)

Related Questions