I was wondering what the recommended way is to persist user settings with SwiftData?
It seems the SwiftData API is focused around querying for multiple objects, but what if you just want one UserSettings object that is persisted across devices say for example to store the user's age or sorting preferences.
Do we just create one object and then query for it or is there a better way of doing this?
Right now I am just creating:
import SwiftData
@Model
final class UserSettings {
var age: Int = 0
var sortAtoZ: Bool = true
init(age: Int = 0, sortAtoZ: Bool = true) {
self.age = age
self.sortAtoZ = sortAtoZ
}
}
In my view I am doing as follows:
import SwiftUI
import SwiftData
struct SettingsView: View {
@Environment(\.modelContext) var context
@Query var settings: [UserSettings]
var body: some View {
ForEach(settings) { setting in
let bSetting = Bindable(setting)
Toggle("Sort A-Z", isOn: bSetting.sortAtoZ)
TextField("Age", value: bSetting.age, format: .number)
}
.onAppear {
if settings.isEmpty {
context.insert(UserSettings(age: 0, sortAtoZ: true))
}
}
}
}
Unfortunately, there are two issues with this approach:
- I am having to fetch multiple items when I only ever want one.
- Sometimes when running on a new device it will create a second UserSettings while it is waiting for the original one to sync from CloudKit.
AppStorage is not an option here as I am looking to persist for the user across devices and use CloudKit syncing.