gpt4 book ai didi

ios - SwiftUI - NavigationView 中的内存泄漏

转载 作者:行者123 更新时间:2023-12-01 15:20:02 25 4
gpt4 key购买 nike

我正在尝试向模态呈现的 View 导航栏添加一个关闭按钮。但是,解雇后,我的 View 模型 初始化 方法永远不会被调用。我发现问题在于它捕获了 自我 导航栏项 的。我不能只通过 weak self导航栏项 的 Action ,因为 View 是一个结构,而不是一个类。这是一个有效的问题还是只是缺乏知识?

struct ModalView: View {

@Environment(\.presentationMode) private var presentation: Binding<PresentationMode>
@ObservedObject var viewModel: ViewModel

var body: some View {

NavigationView {
Text("Modal is presented")
.navigationBarItems(leading:
Button(action: {
// works after commenting this line
self.presentation.wrappedValue.dismiss()
}) {
Text("close")
}

)
}
}
}

最佳答案

您不需要在自己的 View 中拆分关闭按钮。您可以通过添加 capture list 来解决此内存泄漏。到 NavigationView 的关闭:这将打破保留您的 viewModel 的引用周期.

您可以在 Playground 中复制/粘贴此示例代码以查看它是否解决了问题(Xcode 11.4.1,iOS Playground)。

import SwiftUI
import PlaygroundSupport

struct ModalView: View {
@Environment(\.presentationMode) private var presentation
@ObservedObject var viewModel: ViewModel

var body: some View {
// Capturing only the `presentation` property to avoid retaining `self`, since `self` would also retain `viewModel`.
// Without this capture list (`->` means `retains`):
// self -> body -> NavigationView -> Button -> action -> self
// this is a retain cycle, and since `self` also retains `viewModel`, it's never deallocated.
NavigationView { [presentation] in
Text("Modal is presented")
.navigationBarItems(leading: Button(
action: {
// Using `presentation` without `self`
presentation.wrappedValue.dismiss()
},
label: { Text("close") }))
}
}
}

class ViewModel: ObservableObject { // << tested view model
init() {
print(">> inited")
}

deinit {
print("[x] destroyed")
}
}

struct TestNavigationMemoryLeak: View {
@State private var showModal = false
var body: some View {
Button("Show") { self.showModal.toggle() }
.sheet(isPresented: $showModal) { ModalView(viewModel: ViewModel()) }
}
}

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.setLiveView(TestNavigationMemoryLeak())

关于ios - SwiftUI - NavigationView 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61303466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com