关闭 Swiftui 视图后如何清理环境对象?

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

我有一个相当大的项目,我从故事板和 xib 开始。现在我正在使用 swiftui 实现一些新视图。这是我用来执行此操作的代码:

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

但是当我关闭(向下滑动)视图并再次打开它时我遇到了问题,每次我这样做都会创建环境对象的额外副本,这个对象是一个 class 处理tcp连接,简码如下:

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
}}

观点是这样的:

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)
        }
      }}

刚刚通过用 ObservedObject 替换 EnvironmentObject 并将其添加到 ScheduleController 的 deinit 方法解决了这个问题

deinit() {
    connection.cancel()
}