SwiftUI - NavigationView中的内存泄漏问题

13

我想在模态呈现的视图的导航栏中添加一个关闭按钮。 但是,在关闭后,我的视图模型的< strong>deinit方法从未被调用。 我发现问题出在捕获< strong>self在navigationBarItem的地方。 我不能只将弱引用的weak self传递到navigationBarItem的操作中,因为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")
                }

            )
        }
    }
}
4个回答

8

您不需要将关闭按钮拆分到自己的视图中。您可以通过在NavigationView的闭包中添加捕获列表来解决此内存泄漏问题:这将打破保留viewModel的引用循环。

您可以将此示例代码复制/粘贴到播放器中,以查看它解决了问题(Xcode 11.4.1,iOS播放器)。

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())

3

我的解决方案是:

.navigationBarItems(
    trailing: self.filterButton
)

..........................................

var filterButton: some View {
    Button(action: {[weak viewModel] in
        viewModel?.showFilter()
    },label: {
        Image("search-filter-icon").renderingMode(.original)
    })
}

3
我建议采用设计级解决方案,即将导航栏项目分解成单独的视图组件,从而打破引用循环,避免泄漏。
在 Xcode 11.4 / iOS 13.4 上测试 - ViewModel 被正常销毁。
以下是完整的测试模块代码:
struct CloseBarItem: View { // separated bar item with passed binding
    @Binding var presentation: PresentationMode
    var body: some View {
        Button(action: {
            self.presentation.dismiss()
        }) {
            Text("close")
        }
    }
}

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

    var body: some View {

        NavigationView {
            Text("Modal is presented")
            .navigationBarItems(leading: 
                CloseBarItem(presentation: presentation)) // << decompose
        }
    }
}

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

struct TestNavigationMemoryLeak_Previews: PreviewProvider {
    static var previews: some View {
        TestNavigationMemoryLeak()
    }
}

2

由于在使用navigationBarItems时,我将视图模型传递给了用作导航栏项目的视图,导致内存泄漏问题严重。

深入探究后,我了解到navigationBarItems已经被废弃

我曾经

        .navigationBarItems(trailing:
            AlbumItemsScreenNavButtons(viewModel: viewModel)
        )

替代方法是toolbar

我的现有用法如下:

        .toolbar {
            ToolbarItemGroup(placement: .navigationBarTrailing) {
                AlbumItemsScreenNavButtons(viewModel: viewModel)
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接