Hello,
I am experiencing high CPU usage and performance issues when adding new records (StudyLog) in my Swift-based app that uses SwiftData for data management. Here’s a summary of the situation:
-
Data structure: The app manages two main entities:
Subject
(around 10 instances)StudyLog
(around 1000 instances), which has a relationship withSubject
.
-
Issue: When I add a new
StudyLog
, I notice significant CPU rises to nearly 40 % for extended periods of time (sometimes longer than 10 minutes). While I don’t expect it to be instant, the current performance degradation seems abnormal, especially with this amount of data. -
Environment:
- SwiftData is being used to manage the models, and I am fetching all data using
Query
. - I am running the app on on both a simulator and a real device.
- SwiftData is being used to manage the models, and I am fetching all data using
-
Models:
@Model
class Subject: Identifiable, Codable, Equatable, Hashable {
@Attribute(.unique) var id: String
var name: String
var color: String
var order: Int
var doCount: Bool
@Relationship(deleteRule: .cascade) var studyLogs: [StudyLog]?
init(name: String, color: String, order: Int, doCount: Bool) {
self.id = UUID().uuidString
self.name = name
self.color = color
self.order = order
self.doCount = doCount
}
//Equatable, Hashable, Codable, Transferable
}
@Model
class StudyLog: Identifiable, Hashable {
var date: Date
var hour: Int
@Relationship var subject: Subject
init(date: Date, hour: Int, subject: Subject){
self.date = date
self.hour = hour
self.subject = subject
}
// Hashable
}
- View:
struct ContentView: View {
@Environment(Settings.self) var settings
@Query private var studyLogs: [StudyLog]
@Query private var subjects: [Subject]
var body: some View {
//body
}
}
Key Questions:
- Are there any optimizations I should implement when dealing with
SwiftData
and relationships to improve performance when adding records? - Is this level of CPU usage expected, or could I be missing something critical?
Any insights or suggestions on how to diagnose and resolve this would be greatly appreciated.
Thank you in advance!