Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - SwiftUI - Possible Memory Leak

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")
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...