2

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
            }
    }
}
bodich
  • 1,708
  • 12
  • 31
  • Change `StateObject` to`ObservedObject` – Kudos Sep 22 '22 at 13:44
  • @Kudos That can't cut the retain cycle. Though tried anyway just in case and it broke the proper connection with MyObject at all (and of course retain cycle is still there) ))) ObservedObject is using for dependency injection. There is no any here, View creates MyObject by itself. – bodich Sep 22 '22 at 13:50

0 Answers0