如何在视图外使用@Fetchrequest [英] How to use @Fetchrequest outside a View

查看:109
本文介绍了如何在视图外使用@Fetchrequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的@fetchrequest属性移到一个辅助类,该类不是 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.

有人可以帮助我吗?

这是我的代码示例:

ViewModel:

ViewModel:

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

视图:


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 ?? "")
        }

    }
}

谢谢!

推荐答案

@FetchRequest DynamicProperty ,而后者是


/// 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 {


因此,尝试在 View 之外使用它至少是出于设计目的。如果确实是用例,则可以像以前在UIKit + CoreData中一样直接使用 NSFetchRequest 并将结果与​​SwiftUI View手动集成。

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.

这篇关于如何在视图外使用@Fetchrequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆