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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@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(),
]
}
}
</code>
<code>@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(), ] } } </code>
@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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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")
}
}
</code>
<code>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") } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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")
}
}
}
</code>
<code>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") } } } </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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())
}
}
}
}
}
}
}
</code>
<code>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()) } } } } } } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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")
}
}
}
}
}
}
}
}
</code>
<code>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") } } } } } } } } </code>
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?

3

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>let _ = Self._printChanges()
</code>
<code>let _ = Self._printChanges() </code>
let _ = Self._printChanges()

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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.
...
</code>
<code>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. ... </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
}
}
}
</code>
<code>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) } } } </code>
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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật