I found a way to achieve deletion, saving context and make cascade deleteRule working. I'm not sure why it works but it does.
This is particular useful for custom ModelContext where autoSave is disabled.
First, I make sure that the autoSave feature is disabled.
Next, I delete all the models in a single transaction which allows the deletion of child models by cascade.
Then I rollback the context. At this step, child models are deleted but not parents. That's why I finally delete models in a new transaction.
I know that it's not ideal but It seems to work waiting for a fix.
This is my workaround :
extension ModelContext {
/// Deletes models from ModelContext and saves changes to the persistent storage.
/// - Parameter models: the models to delete.
/// - Warning: This method is a workaround for deleting models and saving context since explicitly saving context prevents `cascade` delete rule to work.
public func deleteAndSave<T: PersistentModel>(_ models: [T]) throws {
func deleteModels() {
for model in models {
delete(model)
}
}
let initialAutosaveState = autosaveEnabled
autosaveEnabled = false
try transaction {
deleteModels()
rollback()
}
try transaction {
deleteModels()
}
autosaveEnabled = initialAutosaveState
}
}
Post
Replies
Boosts
Views
Activity
I found out that explicitly saving the modelContext prevents the cascade deleteRule to work.
I filled a Feedback report : FB13640004.
Still an issue in iOS 17 beta 7.
Although we can configure a ModelContainer with a cloudKitDatabase set to none, it still enables CloudKit and automatic sync on it's own.
ModelConfiguration(cloudKitDatabase: ModelConfiguration.CloudKitDatabase.none)
This is still an issue with iOS 17 beta 3.