我应该如何绑定到 SwiftUI 视图中的核心数据实体字符串属性? [英] How should I bind to a Core Data Entity String Attribute within a SwiftUI view?

查看:30
本文介绍了我应该如何绑定到 SwiftUI 视图中的核心数据实体字符串属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 SwiftUI 视图:

Here is my SwiftUI view:

struct EditEntity: View {
    @State var entity: Entity
    var body: some View {
        Form {
            TextField("Entity Name", text: $entity.name)
        }
    }
}

Entity 是 Core Data 使用代码生成为我创建的对象.

Entity is an object Core Data is creating for me using code generation.

以下是该实体在 Core Data 模型文件中的设置方式:

And here is how that entity is set up in the Core Data model file:

我遇到的问题是 $entity.nameBinding 对象,当 SwiftUI 需要 Binding 对象.所以我收到这个编译错误:

And the issue I am having is that $entity.name is a Binding<String?> object, when SwiftUI wants a Binding<String> object. So I am getting this compile error:

无法转换类型为Binding"的值到预期的参数类型 'Binding'

那么有谁知道最好的做法是什么?我应该在属性的视图类中创建一个单独的非可选变量吗?从我的屏幕截图中可以看出,我将该属性设置为非可选,希望它是一个非可选字符串,但显然这不起作用.

So does anyone know what the best practise is for this? Should I create a seperate non-optional variable within the view class for the attribute? As can be seen in my screenshot, I set the attribute to not be optional in the hope it would be a non-optional string, but clearly that didn't work.

我发现这个问题基本上是在这里提出的.答案是创建一个扩展.当尝试将 SwiftUI 与 Core Data 一起使用来做这样一个基本的事情时,真的需要这样做吗?

I found essentially this question asked here. And the answer there is to create an extension. Is this really what needs to be done when trying to use SwiftUI with Core Data together to do such a basic thing?

推荐答案

以下内容应该会有所帮助:

The following should help:

TextField("Entity Name", text: Binding($entity.name)!)

这篇关于我应该如何绑定到 SwiftUI 视图中的核心数据实体字符串属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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