SwiftUI-可能的内存泄漏 [英] SwiftUI - Possible Memory Leak

查看:125
本文介绍了SwiftUI-可能的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始研究SwiftUI,并完成了一些建议根据状态交换视图的教程(请参见下面的代码段).但是,我在调试时注意到,即使是最基本的UI,内存使用也会缓慢增加.这可能只是缺乏知识,但是用SwiftUI以这种方式交换视图是错误的吗?

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

推荐答案

您的代码似乎是完全可以接受的SwiftUI,并且在来回切换时(即使使用手动Toggle()而不是asyncAfter()调用)会导致内存增加.

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.

我相信这是List的错误,因为如果将List更改为另一种视图类型,该问题将消失,并且当在所有其他类型的视图中使用相同的模式时,我没有注意到它.

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.

我建议您向Apple提出反馈意见,并在此处发布反馈号,以便其他受影响的人可以提出反馈自己参考.

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

这篇关于SwiftUI-可能的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆