Skip to main content

How to completely reset a SwiftData ModelContainer

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

How to completely reset a SwiftData ModelContainer 관련

SwiftData by Example

Back to Home

How to completely reset a SwiftData ModelContainer | SwiftData by Example

How to completely reset a SwiftData ModelContainer

Updated for Xcode 15

If you want to delete and destroy all SwiftData objects – every instance of every model belonging to a specific container – you might think you should should call the deleteAllData() of ModelContainer. However, that is quite unhelpful as of iOS 17.0: the method call succeeds, but all that happens is SwiftData disconnects from its underlying data store with your data being unchanged – next time you create the same container it will all be back.

Important

I’m saying that again for folks who think skim reading is cool: at the time of writing deleteAllData() won’t do what you expect.

Instead, you need to call the delete(model:) method of your model context once for each model type you have, without providing any predicate that would otherwise limit which objects are destroyed.

For example, if you use Country and City models, you’d use this:

do {
    try modelContext.delete(model: Country.self)
    try modelContext.delete(model: City.self)
} catch {
    print("Failed to clear all Country and City data.")
}

This doesn’t strictly reset your model container completely, however: all the table definitions and other data will be intact, they’ll just be empty.


이찬희 (MarkiiimarK)
Never Stop Learning.