SwiftData Autosave and Last Updated Timestamp

I have in my model a date created attribute and a date last updated attribute. When adding a new item, I set both to the current timestamp. However, on an update I would like to be able to have the autosave option auto-update the last updated date automatically. Turning off autosave and doing it manually is challenging to get right.

Does anyone know of a solution to this such as extending ModelContext? It seems like last updated date would be a common model requirement.

Self solved... I turned off autosave then used List with the selection option and saved with last updated date modified onChange of the selection when the old selection had hasChanges = true. Essentially autosaves on selection change. Also did the same if the view disappeared via onDisappear. macOS app BTW

The ModelContext emits the willSave and didSave events to the NotificationCenter. You can observe these and set a last updated time on your models. Each event includes the insertions, updates, and deletions which can come in handy.

SwiftData Autosave and Last Updated Timestamp
 
 
Q