if let subLists = todoItem.sub?.allObjects as? [ToDoSubModel] { ForEach(subLists.indices, id: \.self) { index in let item = subLists[index] Divider() HStack { Image(systemName: item.isChecked ? "checkmark.circle.fill" : "circle") .foregroundColor(item.isChecked ? settingsVM.ThemeColors[settingsVM.themeColorNum].color : Color(uiColor: .secondaryLabel)) .onTapGesture { subLists[index].isChecked.toggle() // 反转 isChecked 值 } } } }这段代码的子实体的值更改了但视图没有刷新
时间: 2024-01-17 21:05:52 浏览: 73
LyX lshort.pdf
在这段代码中,当你更改子实体的值后,你需要调用NSManagedObjectContext的save()方法将更改保存到持久化存储中,以便Core Data可以更新视图。你可以像这样修改代码:
```
if let subLists = todoItem.sub?.allObjects as? [ToDoSubModel] {
ForEach(subLists.indices, id: \.self) { index in
let item = subLists[index]
Divider()
HStack {
Image(systemName: item.isChecked ? "checkmark.circle.fill" : "circle")
.foregroundColor(item.isChecked ? settingsVM.ThemeColors[settingsVM.themeColorNum].color : Color(uiColor: .secondaryLabel))
.onTapGesture {
subLists[index].isChecked.toggle()
do {
try viewContext.save() // 保存更改到持久化存储
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
}
}
```
当你更改子实体的值时,调用save()方法将更改保存到持久化存储中,因此Core Data可以更新视图。如果仍然无法更新视图,请检查是否在正确的上下文中调用save()方法。
阅读全文