为什么我替换的 Core Data .sqlite 文件在应用程序再次重新启动之前不起作用?

问题描述 投票:0回答:0

这是我定义 CoreDataManager 的方式

class CoreDataManager {
    static var shared = CoreDataManager()
    
    private let container: NSPersistentContainer
    
    lazy var defaultContext : NSManagedObjectContext = {
        let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        context.parent = rootContext
        context.setupDefaultContext()
        context.obtainPermanentIdsBeforeSaving()
        return context
    }()
    
    lazy var rootContext : NSManagedObjectContext = {
        let context = self.container.viewContext
        context.obtainPermanentIdsBeforeSaving()
        context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
        return context
    }()
    
    private let options: NSPersistentStoreDescription = {
        let options = NSPersistentStoreDescription()
        options.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption)
        options.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption)
        return options
    }()
    
    private let url: URL = {
        let containerUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: SharedGroupName)!
        let url = containerUrl.appendingPathComponent("MyApp.sqlite")
        return url
    }()
    
    init() {
        container = NSPersistentContainer(name: "MyApp")
        container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: url), options]
        container.loadPersistentStores { _, error in
            if let error { fatalError(error.localizedDescription) }
        }
    }
    
    func replaceDatabase() {
        if let oldUrl = container.persistentStoreDescriptions.first?.url {
            let coordinator = container.persistentStoreCoordinator
            coordinator.performAndWait {
                if let newUrl = Bundle.main.url(forResource: "MyApp", withExtension: ".sqlite") {
                    do {
                        try coordinator.replacePersistentStore(at: oldUrl, withPersistentStoreFrom: newUrl, type: .sqlite)
                    } catch {
                        print("❌ error \(error)")
                    }
                }
            }
        }
    }
}

这就是我在代码中的调用方式:

private func replaceDatabaseOnce() {
    if !UserDefaults.bool(forKey: "Done") {
        let manager = CoreDataManager.shared
        manager.replaceDatabase()
        UserDefaults.set(object: true, forKey: "Done")
    }
}

当我在更换后尝试获取任何东西时,它不起作用。看起来数据库是空的。但是当我重新启动应用程序时它会改变。然后一切都很好。用以前的启动替换数据库工作正常。有没有办法让它在不重新启动应用程序的情况下工作?

ios swift core-data
© www.soinside.com 2019 - 2024. All rights reserved.