在 AppDelegate 中为其他 Viewcontroller 初始化 managedContect

Initialize managedContect in AppDelegate for other Viewcontroller

我想初始化 managedObject,但我总是得到这个错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我想使用 Core Data / managedObject 的 ViewController 不是我的启动 ViewController,而是我通过启动 ViewController 访问的另一个 (PortfolioVC)。

这是我的代码:

import Foundation
import CoreData

class DatabaseController {
    private let modelName: String

    init(modelName: String) {
        self.modelName = modelName
    }

    lazy var managedContext: NSManagedObjectContext = {
        return self.storeContainer.viewContext
    }()

    private lazy var storeContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: self.modelName)
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                print("Unresolved error \(error), \(error.userInfo)")
            }
        }
        return container
    }()

    func saveContext () {
        guard managedContext.hasChanges else { return }

        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Unresolved error \(error), \(error.userInfo)")
        }
    }
}

这是我的 AppDelegate:

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    lazy var coreDataStack = DatabaseController(modelName: "Portfolio")

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        guard let navController = window?.rootViewController as? UINavigationController,
            let viewController = navController.topViewController as? PortfolioVC else {
                return true
        }
        viewController.managedContext = coreDataStack.managedContext
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {

    }

    func applicationDidEnterBackground(_ application: UIApplication) {

        coreDataStack.saveContext()
    }

    func applicationWillEnterForeground(_ application: UIApplication) {

    }

    func applicationDidBecomeActive(_ application: UIApplication) {

    }

    func applicationWillTerminate(_ application: UIApplication) {

        coreDataStack.saveContext()
    }


}

这是 PortfolioVC 中的代码:

导入 UIKit 导入核心数据

class PortfolioVC: UIViewController {


    var managedContext: NSManagedObjectContext!
    var namePortfolio: NamePortfolio?

override func viewDidLoad() {
        super.viewDidLoad()
        tableViewPortfolio.dataSource = self

        let standardPortfolio = "Watchlist"
        let fetchRequest: NSFetchRequest<NamePortfolio> = NamePortfolio.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(NamePortfolio.name), standardPortfolio)

        do {
            let results = try managedContext.fetch(fetchRequest) // here I get the error (managedContext = nil)
            if results.count > 0 {
                // Portfolio already created
                namePortfolio = results.first

            } else {
                // no Portfolio
                namePortfolio = NamePortfolio(context: managedContext)
                namePortfolio?.name = standardPortfolio
                try managedContext.save()
            }
        }  catch let error as NSError {

            print("Could not fetch \(error), \(error.userInfo)")
        }

    }

非常感谢您的帮助!

didFinishLaunchingWithOptions中的代码运行时,PortfolioVC还没有被添加到导航控制器堆栈(甚至实例化),所以守卫失败。有两种方法可以将 managedContext 获取到 PortfolioVC:

a) 在 didFinishLaunchingWithOptions 中将它传递给启动视图控制器,然后使用 prepareForSegue 从那里将它传递给 PortfolioVC。您需要将 managedContext 属性 添加到您的启动 VC,即使您只需要将它传递到投资组合 VC.

b) 在 PortfolioVC 中,获取对 AppDelegate 的引用,然后从那里获取 managedContext。

    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
        managedContext = appDelegate.coreDataStack.managedContext
    }

关于哪一个是更好的设计模式,意见不一。