如何在视图外使用@Fetchrequest

时间:2020-02-06 19:01:23

标签: swift core-data swiftui ios13

我试图将@fetchrequest属性移到一个非View的辅助类中,但是每次尝试这样做时,都会收到一条错误的指令错误。

有人可以帮助我吗?

这是我的代码的示例:

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

    }
}

谢谢!

2 个答案:

答案 0 :(得分:3)

@FetchRequestDynamicProperty,后者是

/// 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手动集成。

答案 1 :(得分:0)

在尝试弄清楚自己如何取得类似结果时,我遇到了您的问题。我想您现在可能已经破解了,但是为了那些在同一问题上绊脚石的人的帮助,我将去回答,或者至少指向可能找到答案的地方:-)

如前所述,import keras from .models.all_models import model_from_name def model_from_checkpoint_path(model_config, latest_weights): model = model_from_name[model_config['model_class']]( model_config['n_classes'], input_height=model_config['input_height'], input_width=model_config['input_width']) model.load_weights(latest_weights) return model def resnet_pspnet_VOC12_v0_1(): model_config = { "output_height": 96, "input_height": 384, "input_width": 576, "n_classes": 151, "model_class": "resnet50_pspnet", "output_width": 144 } REPO_URL = "https://github.com/divamgupta/image-segmentation-keras" MODEL_PATH = "pretrained_model_1/r2_voc12_resnetpspnet_384x576.24" model_url = "{0}/releases/download/{1}".format(REPO_URL, MODEL_PATH) latest_weights = keras.utils.get_file(model_url.split("/")[-1], model_url) return model_from_checkpoint_path(model_config, latest_weights) 属性包装器在View组件之外不起作用(这似乎有些奇怪的功能遗漏)

我发现最好的替代方法是与@FetchRequest发布者实施基本上相同的操作,以Apostolos在其答案here中建议的Combine更新并在链接的Medium post

中进行了详细说明

我整理了一个简单的概念验证示例,用于测试和演示iOS14及其新生命周期管理的方法。可以在我的GitHub存储库中的here

上找到该演示应用程序

祝你好运。