提问者:小点点

SwiftUI-EnvironmentObject-奇怪的内存使用


在我的SwiftUI应用程序中,我得到了一些奇怪的内存使用结果。 下面你可以看到我构建的一个最小的例子。

/// Test file for strange behaviour with EnvironmentObject
/// The RAM Usage is increased if we click the button in View "Settings" and switch back to "MapView"

import SwiftUI
import MapKit

class Model: ObservableObject {
    @Published var coolBool: Bool = false {
        didSet {
            print(coolBool.description)
        }
    }
}

struct MapView: UIViewRepresentable {
    private let mapView = MKMapView(frame: .zero)
    
    func makeUIView(context: Context) -> MKMapView {
        return mapView
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {

    }
}

struct Settings: View {
    @EnvironmentObject var model: Model
    
    var body: some View {
        Form {
            Button(action: {self.model.coolBool.toggle()}) {
                Text(self.model.coolBool.description)
            }
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var model: Model
    
    var body: some View {
        TabView() {
            MapView().tabItem {
                Image(systemName: "map")
                Text("1")
            }
            Settings().tabItem {
                Image(systemName: "gear")
                Text("2")
            }
            Text("Just a screen").tabItem {
                Image(systemName: "sunrise")
                Text("3")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

场景:

  1. 打开应用程序
  2. 您将看到MapView,内存使用稳定
  3. 转到选项卡2
  4. 单击将更改EnvironmentObject的按钮,内存使用仍然稳定
  5. 转到选项卡3,内存使用相同
  6. 转到选项卡1(MapView),内存使用增加

如果你重做3,4,6,你会看到内存使用量越来越大。 有人能给我解释一下吗? 如果我点击按钮->,内存使用量将从大约40 MB开始; 转到MapView->; 点击按钮->; 转到MapView->; 。。。。 内存使用量将增加。 我得到了大约500 MB的内存使用量


共1个答案

匿名用户

请尝试以下操作

struct MapView: UIViewRepresentable {

    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)        // created here is managed by SwiftUI
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {

    }
}