如何在 AppDelegate 中初始化核心数据的持久容器并在整个应用程序中使用它?

How do I initialize the Core Data's persistent container in AppDelegate and use it throughout the app?

我正尝试在核心数据应用的多个视图控制器中使用 NSPersistentContainer

最初,我在单个视图控制器中设置了容器,效果很好:

第一个视图控制器

var container: NSPersistentContainer!

container = NSPersistentContainer(name: "MyCoreData")
container.loadPersistentStores { storeDescription, error in
    self.container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

    if let error = error {
        print("Unresolved error \(error.localizedDescription)")
    }
}

但是,我根据 Apple 的 documentation:

将此代码迁移到 AppDelegate

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "MyCoreData")
        container.loadPersistentStores { description, error in
            container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
            if let error = error {
                fatalError("Unable to load persistent stores: \(error)")
            }
        }
        return container
    }()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if let firstVC = window?.rootViewController as? FirstViewController {
            firstVC.container = persistentContainer
        }
        
        if let secondVC = window?.rootViewController as? SecondViewController {
            secondVC.container = persistentContainer
        }
        
        return true
    }
}

我的每个视图控制器现在都有一个名为 containerNSPersistentContainer 类型的变量。但是,当我加载视图控制器时,出现以下错误:

Unexpectedly found nil while implicitly unwrapping an Optional value

此错误指向 container.viewContext 所在的位置。更具体地说:

fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: container.viewContext, sectionNameKeyPath: "title", cacheName: nil)

我不确定我是否收到来自 rootViewController 的错误,因为我没有单一的根视图控制器,因为我使用的是标签栏控制器。

我的建议是在 UIViewController 的扩展中 延迟实例化 计算 属性 实际上你只需要托管对象上下文。

extension UIViewController {

    var context : NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }
}

您还可以添加一个 save 函数。