0

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!

4
  • 1
    The property wrapper @SectionedFetchRequest should be used in a view Commented Dec 14, 2024 at 21:28
  • FetchRequestController, it is an absurd amount of code though when you can do it with a 1 line property wrapper Commented Dec 14, 2024 at 22:23
  • Remove the view model class, in SwiftUI view structs are the view models that drive the ui objects Commented Dec 15, 2024 at 0:40
  • You can certainly move the whole CoreData stuff into an observable Model (not a ViewModel), and IMHO, this will be the better solution in the long run than any fancy SwiftUI empowered CoreData artefacts, which you can use directly in SwiftUI views. HOWEVER, the way you did this as shown in "For normal fetching", is actually very dangerous and code for plain old CoreData should not be written like this. So, in this case, you are better off using the fancy SwiftUI empowered CoreData artefacts, which are easy to use, and work well for many use cases. Commented Dec 15, 2024 at 12:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.