我已经在我的应用程序中设置了 CoreData 堆栈,但对 NSPersistentContainer 的引用在 PassWordTableVC 中返回 nil。
应用程序委托
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
print("AppDelegate: Application didFinishLaunching")
// Override point for customization after application launch.
if let rootVC = window?.rootViewController as? PassWordTableVC{
rootVC.container = persistentContainer
}
return true
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "PasswordModel")
container.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
return container
}()
PassWordTableVC
var container: NSPersistentContainer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
guard container != nil else{
fatalError("This view needs a persistent container")
}
}
PassWordTableVC viewDidLoad
可能会在 didFinishLaunchingWithOptions
中的代码之前调用。一个简单的解决方案是向您的 didSet
属性添加一个 container
观察者:
var container: NSPersistentContainer! {
didSet {
// do what you currently have in viewDidLoad that needs the container
}
}