0

I've been experimenting with some changes in my project and have been adding and deleting Core Data instances of entities.

Eventually, due to changes in my code, the data already stored in persistent storage became corrupt, it fails to load. Whenever Core Data tries to load my data, the app crashes.

I know what the problem is - I need to delete some instances of core data entities from persistent storage. I can't, however, do it in the simulator by just swipe-deleting, because the app crashes when core data tries to load.

How do I delete everything in persistent storage through code, without loading the storage?

I know there is a function to destroy persistent store, but I honestly can't figure out how and where I am supposed to use it.

I presume I should change the code in my DataController.

Here is how I load NSPersistentContainer (DataController class)

import Foundation
import CoreData

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "iLegal")
    
    init () {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
                return
            }
        }
    }
    
}

I then create a @StateObject of NSPersistentContainer and send it to the environment

import SwiftUI

@main
struct iLegalApp: App {
    
    @StateObject private var dataController = DataController()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, dataController.container.viewContext)
        }
    }
} 

Please help!

Andrei M.
  • 33
  • 3
  • 1
    Does this answer your question? [Mock Core Data object in SwiftUI Preview](https://stackoverflow.com/questions/70482430/mock-core-data-object-in-swiftui-preview) – lorem ipsum Jan 18 '23 at 12:28
  • 1
    https://stackoverflow.com/questions/73094220/how-to-fully-remove-macos-xcode-application/73094334#73094334 – lorem ipsum Jan 18 '23 at 12:31

1 Answers1

0

@lorem-ipsum Thank you! I figured it out!

In my DataController class, I basically rewrote the init() function to:

init () {
    do {
        try container.persistentStoreCoordinator.destroyPersistentStore(at: container.persistentStoreDescriptions.first!.url!, type: .sqlite, options: nil)
        print("Success")
    } catch {

        print(error.localizedDescription)
        print("Fail")
    }

I ran the project, the persistentStore was empty.

I then reverted to:

init () {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
                return
            }
        }
    }
}
Andrei M.
  • 33
  • 3