Using any SwiftData Query causes app to hang

I want to get to a point where I can use a small view with a query for my SwiftData model like this:

@Query
private var currentTrainingCycle: [TrainingCycle]
init(/*currentDate: Date*/) {
_currentTrainingCycle = Query(filter: #Predicate<TrainingCycle> {
$0.numberOfDays > 0
// $0.startDate < currentDate && currentDate < $0.endDate
}, sort: \.startDate)
}

The commented code is where I want to go. In this instance, it'd be created as a lazy var in a viewModel to have it stable (and not constantly re-creating the view). Since it was not working, I thought I could check the same view with a query that does not require any dynamic input. In this case, the numberOfDays never changes after instantiation. But still, each time the app tries to create this view, the app becomes unresponsive, the CPU usage goes at 196%, memory goes way high and the device heats up quickly.

Am I holding it wrong? How can I have a dynamic predicate on a View in SwiftUI with SwiftData?

The way you create a dynamic Query, as shown in your code snippet, doesn't have anything wrong. The SwiftData version of the Adopting SwiftData for a Core Data app sample does the same thing (in TripListView.swift).

To figure out why your app becomes unresponsive, your might consider profiling your app using Instruments.

I'm guessing that the real issue may be that the init is called many times, followed by the view body getter that accesses the query result being triggered many times. You can quickly check if that is the case by adding logs in the following way:

var body: some View {
print("\(#function)")
let _ = Self._printChanges()
...
}

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Thank you for the answer. I'll keep the printing function in mind.

As for my original issue, I later found that it was likely due to 2 embedded NavigationStack. Removing the duplicated inner stack resolved the issue.

I was able to continue, but got another hang with basically the same query. I am at the point where the time I've saved with the more concise syntax of SwiftData has been completely lost to debugging issues. I will revert back to CoreData. Even if it is more code, I feel like I have better control of the behaviour and life cycle.

Using any SwiftData Query causes app to hang
 
 
Q