如何删除 SwiftUI 中标有@ObjectBinding 的对象?

How to delete an object in SwiftUI which is marked with @ObjectBinding?

我想删除一个标记为 @ObjectBinding 的对象,例如为了清理一些 TextFields

我试图将对象引用设置为 nil,但没有成功。

import SwiftUI
import Combine

class A: BindableObject {
    var didChange = PassthroughSubject<Void, Never>()

    var text = "" { didSet { didChange.send() } }
}

class B {
    var property = "asdf"
}

struct DetailView : View {
    @ObjectBinding var myObject: A = A()    //@ObjectBinding var myObject: A? = A() -> Gives an error.
    @State var mySecondObject: B? = B()

    var body: some View {

        VStack {
            TextField($myObject.text, placeholder: Text("Enter some text"))
            Button(action: {
                self.test()
            }) {
                Text("Clean up")
            }
        }
    }

    func test() {
        //myObject = nil
        mySecondObject = nil
    }
}

如果我尝试对 @ObjectBinding 使用可选项,我会收到错误

"Cannot convert the value of type 'ObjectBinding' to specified type 'A?'".

它仅适用于 @State

此致

你可以这样做:

class A: BindableObject {
    var didChange = PassthroughSubject<Void, Never>()

    var form = FormData() { didSet { didChange.send() } }

    struct FormData {
        var firstname = ""
        var lastname  = ""
    }

    func cleanup() {
        form = FormData()
    }
}

struct DetailView : View {
    @ObjectBinding var myObject: A = A()

    var body: some View {

        VStack {
            TextField($myObject.form.firstname, placeholder: Text("Enter firstname"))
            TextField($myObject.form.lastname, placeholder: Text("Enter lastname"))
            Button(action: {
                self.myObject.cleanup()
            }) {
                Text("Clean up")
            }
        }
    }
}

我完全同意 @kontiki ,但你应该记住不要在变量可以外出时使用 @State 。 @ObjectBinding 在这种情况下是正确的方式。如果需要,所有新的内存管理方式都已经包含可选的(弱)。

检查 this 以获取有关 SwiftUI 中内存管理的更多信息

这就是如何使用@ObjectBinding

struct DetailView : View {
    @ObjectBinding var myObject: A 

DetailView(myObject: A())