Search code examples
swiftcore-dataswiftuiios13

How to use @Fetchrequest outside a View


I am trying to move my @fetchrequest property to an auxiliar class, which is not a View, but every time I try to do that, I get a bad instruction error.

Can anyone help me?

This is a sample of my code:

ViewModel:

class ViewModel {
    @FetchRequest(entity: Teste.entity(), sortDescriptors: []) var teste: FetchedResults<Teste>
}

View:


struct ContentView: View {

    let viewModel: ViewModel

    init(viewModel: ViewModel) {
        self.viewModel = viewModel
    }

    var body: some View {

        List(viewModel.teste) { item in // error happens in this line
            Text(item.id ?? "")
        }

    }
}

Thank you!


Solution

  • I came across the your question while trying to figure out how achieve a similar result myself. I'm guessing you may have cracked this by now, but for the benefit of those stumbling across the same question I'll have a go at answering, or at least pointing at where the answer might be be found :-)

    As has been mentioned the @FetchRequest property wrapper doesn't work outside of View components (which seems a bit of an odd functional omission)

    The best alternative I've found is to implement essentially the same thing with a Combine publisher for updates from the NSFetchedResultsController as suggested by Apostolos in his answer here and detailed in a linked Medium post

    I've put together a simple proof of concept example that tests and demonstrates the approach with iOS14 and its new life cycle management. This demo app can be found in my GitHub repo over here

    Good luck.