13

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 Answers1

5

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.

John M.
  • 8,892
  • 4
  • 31
  • 42
  • 4
    Thanks John. I tested a few more components and found issues with List, ScrollView, Form and NavigationViews using the same example. Reference #: FB7318839 – WafflesRightMeow Sep 24 '19 at 03:37
  • For me it's two tabs with empty NavigationViews. Switching between tabs increases memory usage. – Alex Oct 23 '19 at 05:54
  • I was seeing a similar issue. This appears to have been resolved with Big Sur 11.0.1 - formal release, not the Beta RC version. – Philip Pegden Nov 16 '20 at 09:27
  • Same here on iOS 14.2 with TabViews PageTabViewStyle ... every time you switch pages the memory usage goes up – MaximeHeckel Nov 28 '20 at 15:33