In the following example, changes to my UserGroup
aren’t saved and don’t update the UI.
Upon tapping the user’s id, the function to change the id is called, but the user’s id is never updated and the UI never changes.
In the following code:
User
: A simple user objectUserGroup
: an@Model
object that stores a list of usersMyViewModel
: A view model that stores aUserGroup
and has a function to update the ID of a user in the group. ThemodelContext
property is there because I get errors if I remove itMain
: A view that display’s a user’sid
and changes theid
when tapped
@Observable class User: Codable {
var id: String
init() {
self.id = UUID().uuidString
}
}
@Model
class UserGroup {
var users: [User]
init() {
self.users = [User()]
}
}
@Observable class MyViewModel {
var modelContext: ModelContext
var userGroup: UserGroup()
init(modelContext: ModelContext) {
self.modelContext = modelContext
self.userGroup = UserGroup()
}
func generateNewId() {
userGroup.users[0].id = UUID().uuidString
}
}
struct Main: View {
@Environment(.modelContext) var modelContext
@State var viewModel: MyViewModel?
var body: some View {
ZStack {
if viewModel != nil {
Text(viewModel!.dataModel.users[0].id)
.onTapGesture {
viewModel!.generateNewId()
}
}
}
.onAppear { viewModel = MyViewModel(modelContext: modelContext) }
}
}
Instead of changing the id property of a user in userGroup.users through userGroup.users[0].id = , I tried reassigning it using userGroup.users[0] = User(). This got the user’s id to successfully change, but didn’t update the UI until I restarted the app.
I also tried making UserGroup a vanilla, non-@Model class (not stored in SwiftData), which solved the issue, making me believe it’s a SwiftData related issue.
I’ve tried to minimize the example and recreate it in a fresh project so I don’t believe this is due to any other files or messed up SwiftData configurations. Why are my changes not saving or updating the UI, and how can I fix it?
charlie reeder is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.