swiftuipredicateswiftdata

What is causing a memory leak when including an arbitrary predicate filter?


Edit: I have figured out the memory use is continuously increasing. Just need to figure out why...

I ran into an issue while creating a simple app. I recreated the problem here using the below code. Here, the domain class is named TestModel.

@Model
class TestModel {
  var startedAt: Date
  var endedAt: Date
  
  init(startedAt: Date = .now, endedAt: Date = .distantPast) {
    self.startedAt = startedAt
    self.endedAt = endedAt
  }
  
  static var samples: [TestModel] {
    [
      TestModel(),
    ]
  }
}

These objects are displayed in the following simple view composed of just a couple date pickers bound to the model object.

struct TestModelDetails: View {
  
  @Environment(\.dismiss)
  private var dismiss
  
  @AppStorage("activeModelId")
  private var activeModelId: Double?
  
  @Bindable
  var testModel: TestModel
  
  var body: some View {
    VStack {
      DatePicker("Started at", selection: $testModel.startedAt)
      DatePicker("Ended at", selection: $testModel.endedAt)
      Button("Complete") {
        testModel.endedAt = .now
        activeModelId = nil
        dismiss()
      }
    }
    .navigationTitle("Test Model Details")
  }
}

The following class is a wrapper class to view a specific object using a query.

struct QueriedTestModelDetails: View {
  
  @Environment(\.modelContext)
  private var context
  
  @Query
  private var testModels: [TestModel]
  
  init(startedAt: Date) {
    let byStartedAt = #Predicate<TestModel> { $0.startedAt == startedAt }
    _testModels = Query(filter: byStartedAt)
  }
  
  var body: some View {
    if let testModel = testModels.first {
      TestModelDetails(testModel: testModel)
    } else {
      ContentUnavailableView("Error", systemImage: "moon")
    }
  }
}

The below view is used to select a specific object to view details for

struct TestModelList: View {
  
  @Environment(\.modelContext)
  private var context
  
  @Query
  private var testModels: [TestModel]
  
  init() {
    let byStartedAt = #Predicate<TestModel> { tm in
      true
    }
    _testModels = Query(filter: byStartedAt)
  }
  
  var body: some View {
    List {
      ForEach(testModels) { tm in
        NavigationLink(destination: TestModelDetails(testModel: tm)) {
          VStack {
            Text("Test Model")
            HStack {
              Text(tm.startedAt.formatted())
              Spacer()
              Text(tm.endedAt.formatted())
            }
          }
        }
      }
    }
  }
}

And, finally, this view ties it all together. The button on the toolbar toggles the view to display the active model object or you can select one from the list.

struct TestModelListView: View {
  
  @Environment(\.modelContext)
  private var context: ModelContext
  
  @AppStorage("activeModelId")
  private var activeModelId: Double?
  
  @State
  private var showActiveTestModelDetails: Bool = false
  
  @State
  private var dateFilter: Date = .now
  
  var body: some View {
    NavigationStack {
      VStack {
        DatePicker("Date", selection: $dateFilter, displayedComponents: [.date])
          .datePickerStyle(GraphicalDatePickerStyle())
        TestModelList()
          .navigationDestination(isPresented: $showActiveTestModelDetails, destination: {
            if let activeModelId = activeModelId {
              let startedAt = Date(timeIntervalSinceReferenceDate: activeModelId)
              QueriedTestModelDetails(startedAt: startedAt)
            }
          })
          .navigationTitle("Journal")
          .toolbar {
            ToolbarItem {
              Button {
                if activeModelId == nil {
                  let newTestModel = TestModel()
                  context.insert(newTestModel)
                  activeModelId = newTestModel.startedAt.timeIntervalSinceReferenceDate
                }
                
                showActiveTestModelDetails = true
              } label: {
                if activeModelId == nil {
                  Text("START")
                } else {
                  Text("CONTINUE")
                }
              }
            }
          }
      }
    }
  }
}

This is my issue which I am not understanding. When I include the filter predicate into my query to test models in TestModelList, even this arbitrary one, my app freezes upon any navigation action. Does anyone know what I am doing wrong here? Or how I can debug this problem?


Solution

  • You have a problem with endless SwiftUI state change loops.

    To analyze such problems, I recommend to start by inserting a _printChanges call into the body of your SwiftUI views. This makes it visible when and why the layout process of a SwiftUI view is triggered.

    let _ = Self._printChanges()
    

    In your case, after tapping on “Start”, you will see that you have a problem in your TestModelList implementation:

    TestModelList: @self changed.
    TestModelList: @dependencies changed.
    TestModelList: @self changed.
    QueriedTestModelDetails: @self, @identity, _context, @128, @144 changed.
    TestModelDetails: @self, @identity, _dismiss changed.
    TestModelList: @self changed.
    TestModelList: @self changed.
    TestModelList: @self changed.
    TestModelList: @self changed.
    ...
    

    TestModelList is in an infinite loop here, as you can see.

    You must ensure that the list and detail view do not influence each other in a loop and you have several suspicious code parts in this regard.

    For example, every change to activeModelId causes TestModelDetails to be re-rendered due to the AppStorage property wrapper. And every change to TestModelDetails can cause the ForEach list in TestModelList to be rebuilt in because of the way you're using NavigationLink.

    This can lead to the aforementioned endless loops.

    Here's how you can prevent the NavigationLink issue in your TestModelList.

    struct TestModelList: View {
        @Environment(\.modelContext)
        private var context
    
        @Query
        private var testModels: [TestModel]
    
        init() {
            let byStartedAt = #Predicate<TestModel> { tm in
                true
            }
            _testModels = Query(filter: byStartedAt)
        }
    
        var body: some View {
            List(testModels) { model in
                NavigationLink(value: model) {
                    VStack {
                        Text("Test Model")
    
                        HStack {
                            Text(model.startedAt.formatted())
                            Spacer()
                            Text(model.endedAt.formatted())
                        }
                    }
                }
            }
            .navigationDestination(for: TestModel.self) { model in
                TestModelDetails(testModel: model)
            }
        }
    }
    

    Your code may have other problems of this kind, but you should be able to identify them using the above method. To make matters worse, NavigationLink is not particularly forgiving when it comes to this type of problem.

    Also note that you need to be very careful with what you do in the init methods of SwiftUI views. In general, no logic should be executed in them, due to the way SwiftUI generates and uses views on state changes.