swiftswiftuideinit

How to clean up environment object after Swiftui view is dismissed?


I have a fairly large project that I started with storyboards and xibs. Now I'm implementing some new views using swiftui. This is the code I'm using to do that:

func goToSchedule() {
    let scheduleController = ScheduleController()
    let vc = UIHostingController(rootView: ScheduleView().environmentObject(scheduleController))
    if let topController = UIApplication.topViewController() {
        topController.present(vc, animated: true, completion: nil)
    }
}

But I have a problem when I dismiss (swipping down) the view and open it again, every time I do it creates an extra copy of the environment object, this object is a class that handles a tcp connection, the shortened code is as follows:

class ScheduleController: ObservableObject, NetworkDelegate {
    var didChange = PassthroughSubject<Void, Never>()
    @Published var timers = [ScheduleTimer]()
    let connection = tcpNetwork()
    init() {
        connection.delegate = self
    }
    func send(data: String) {
        self.connection.sendMsg(data)
    }
    func processData(data: String) {
    // long function where the received data is parsed and the timers array is updated
}}

The view is this:

struct ScheduleView: View {
@EnvironmentObject var scheduleController: ScheduleController

var body: some View {
    NavigationView {
      List {
        ForEach(scheduleController.timers, id: \.self) { timer in
            TimerRow(id: timer.id, name: timer.name, startTimer: timer.start, endTimer: timer.end, isActive: timer.isActive)
        }
      }}

Solution

  • Just solved this by replacing the EnvironmentObject by an ObservedObject and also by adding this to the deinit method of ScheduleController

    deinit() {
        connection.cancel()
    }