[英]How to clean up environment object after Swiftui view is dismissed?
I have a fairly large project that I started with storyboards and xibs.我有一个相当大的项目,我从故事板和 xib 开始。 Now I'm implementing some new views using swiftui.
现在我正在使用 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:但是当我关闭(向下滑动)视图并再次打开它时出现问题,每次我这样做时都会创建一个环境对象的额外副本,这个对象是一个处理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
}}
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)
}
}}
Just solved this by replacing the EnvironmentObject by an ObservedObject and also by adding this to the deinit method of ScheduleController刚刚通过将 EnvironmentObject 替换为 ObservedObject 并将其添加到 ScheduleController 的 deinit 方法中解决了这个问题
deinit() {
connection.cancel()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.