How to use @Fetchrequest outside a View

孤者浪人 提交于 2020-08-07 03:51:59

问题


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!


回答1:


@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.



来源:https://stackoverflow.com/questions/60101859/how-to-use-fetchrequest-outside-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!