4

I have loaded a specific URL file in persistentContainer using the following:

// MARK: Core Data Stack

lazy var persistentContainer: NSPersistentContainer = {
  os_log("In persistent Container", log: OSLog.default, type: .debug)

  // set URL to game file location
  let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
  let docURL = urls[urls.endIndex-1]
  let storeURL = docURL.appendingPathComponent(Singleton.sharedInstance.mainGameFileName!)

  let container = NSPersistentContainer(name: "RefGameData")
  container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)]
  container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    if let error = error as NSError? {
      fatalError("Unresolved error \(error), \(error.userInfo)")
    }
  })

  return container
}()

I want to remove that particular URL file and replace it with a different file when I need to load a different game's data. I have not be able to locate in the Apple documentation for persistentContainer any equivalent to container.unloadPersistentStores(....)

I am a noobie in Swift programming and any thoughts would be appreciated.

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
HeyRef
  • 61
  • 4

1 Answers1

4

You need to use the persistent store coordinator for that. NSPersistentContainer has a property called persistentStoreController, and that has a method called remove, which does what you're looking for.

Keep in mind that if you remove a persistent store, you must be absolutely sure that you don't have any managed objects in memory that were loaded from that store. They will not be useful any more and might make the app crash if you try to use them.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • I think it's `persistentStoreCoordinator`.: https://developer.apple.com/documentation/coredata/nspersistentcontainer/1640567-persistentstorecoordinator – Manabu Nakazawa May 02 '21 at 07:34