我只想将一个实体添加到现有的 NSManagedObject 数据图并在代码中访问该实体。在这种情况下,我添加了“地址”:
现有代码有效。我只是补充说:
let address = Address(context:self.context!)
...就像最初对 Person() 实体所做的那样。
这是代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
self.context = persistentContainer.viewContext
let storyboard = self.window?.rootViewController?.storyboard
guard let vc = storyboard?.instantiateViewController(withIdentifier: "RootViewController") as? RootViewController
else { fatalError("Cannot instantiate root view controller") }
vc.context = self.context
self.window?.rootViewController = vc // Note: necessary to keep the app del's context instance within vc.
let address = Address(context:self.context!)
let person = Person(context: self.context!)
person.firstName = "Foo"
person.lastName = "Bar"
person.cars = NSSet(array: [
Car(context: self.context!).configured(maker: "VW",
model: "Sharan",
owner: person),
Car(context: self.context!).configured(maker: "VW",
model: "Tiguan",
owner: person)
])
do{
try saveContext()
} catch {
//something bad happened, handle this situation appropriately
}
return true
}
问题:如何让代码看到新实体“地址”?