SwiftUI - Possible Memory Leak

2020-04-07 18:19发布

问题:

I recently started looking into SwiftUI and have run through a few tutorials which recommend swapping views based on state (see the snippet below). However, I noticed while debugging that memory usage slowly creeps up with even the most basic UI. This may just be lack of knowledge but is it wrong to swap views in this sort of manner with SwiftUI?

Version 11.0 (11A420a) - iOS 13

// Memory Leak Test
struct ContentView: View {
    @State private var toggle = false

    func cycleViews() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.toggle = !self.toggle
            self.cycleViews()
        }
    }

    var body: some View {
        Group {
            if toggle {
                ViewA()
            } else {
                ViewB()
            }
        }.onAppear {
            self.cycleViews()
        }
    }
}

struct ViewA: View {
    var body: some View {
        VStack {
            Text("Some Content")
            Text("Some Content")
            Text("Some Content")
            Text("Some Content")
            Text("Some Content")
        }
    }
}

struct ViewB: View {
    var body: some View {
        List {
            Text("Some Content")
            Text("Some Content")
            Text("Some Content")
            Text("Some Content")
            Text("Some Content")
        }
    }
}

回答1:

Your code appears to be perfectly acceptable SwiftUI, and there does appear to be a memory leak somewhere, as switching back and forth (even with a manual Toggle() instead of the asyncAfter() call) leads to increasing memory.

I believe this is a bug with List, because if you change the List to another type of view, the issue disappears, and I haven't noticed it when using this same pattern with all other kinds of views.

I'd recommend you file feedback with Apple, and post the feedback number here so others affected can file their own and reference it.