Re SwiftData: is my understanding correct : generally speaking and by default insert method inserts objects into the context and context automatically persist - e.g. inserts them into container while the delete method does not - it only deletes from context and context does not delete them from the container unless save is called ? It is not clear from the documentation nor from the definitions :
public func delete<T>(model: T.Type, where predicate: Predicate<T>? = nil, includeSubclasses: Bool = true) throws where T : PersistentModel
//How can I test it ?
I’m keen to learn where I can confirm this in Apple’s documentation or official articles, code definitions, apart from experimenting or consulting third-party materials. Where does it explicitly state that SwiftData includes an automatic saving feature but does not offer automatic deletion?
"Meet SwiftData" (WWDC23): Around the 14:30 mark, Apple mentions that SwiftData automatically saves changes "at opportune moments." But nothing is advised re deleting ?
Are we supposed to be taking hints :
"Build an app with SwiftData" (WWDC23): This session demonstrates using context.save() to persist changes after deleting an object, implies the idea that deletion isn't automatic
How to truly learn if you do not have official materials ? This is exact Science, not archeology or history.
I feel like a speleologist.
Apparently it also deletes automatically as per this :
for index in indexSet {
let animalToDelete = animals[index]
if navigationContext.selectedAnimal?.persistentModelID == animalToDelete.persistentModelID {
navigationContext.selectedAnimal = nil
}
modelContext.delete(animalToDelete)
}
}
The sample above uses the SwiftData autosave feature, which is enabled by default when creating a ModelContainerusing the modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:) modifier. If this feature is disabled, the removeAnimals method needs to explicitly save the change by calling the ModelContext method save(); for example:
do {
for index in indexSet {
let animalToDelete = animals[index]
if navigationContext.selectedAnimal?.persistentModelID == animalToDelete.persistentModelID {
navigationContext.selectedAnimal = nil
}
modelContext.delete(animalToDelete)
}
try modelContext.save()
} catch {
// Handle error.
}
}
https://developer.apple.com/documentation/swiftdata/deleting-persistent-data-from-your-app