SwiftUI retain cycle with class

79 Views Asked by At

I have a View which contains some kind of a controller. I need to have ability to trigger View's method from the controller. But I am getting retain cycle that I can't solve. Such View never destroy from memory. Any way to break that retain cycle?

I can't use just Published var inside MyObject in my particular case, example is super basic just to show the point.

class MyObject: ObservableObject {
    var function = { () }
}

struct MyView: View {
    @State var value: Int = 0
    @StateObject var obj = MyObject()

    func viewMethod() { value += 1 }
    
    var body: some View {
        Text("Placeholder")
            .onAppear {
                //Obj holds a strong reference to View.
                obj.function = viewMethod
            }
    }
}
0

There are 0 best solutions below