Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 221
Laura Corssac Avatar asked Feb 06 '20 19:02

Laura Corssac


2 Answers

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.

like image 181
shufflingb Avatar answered Oct 07 '22 12:10

shufflingb


@FetchRequest is a DynamicProperty and latter is

/// Represents a stored variable in a `View` type that is dynamically
/// updated from some external property of the view. These variables
/// will be given valid values immediately before `body()` is called.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicProperty {

So it is, at least, "out of design" to try to use it outside of View. If it is really use-case then use NSFetchRequest directly as previously in UIKit+CoreData and integrate results with SwiftUI View manually.

like image 34
Asperi Avatar answered Oct 07 '22 12:10

Asperi