Core data CoreData:关系:保存:查询
我有Core data CoreData:关系:保存:查询,core-data,save,one-to-many,Core Data,Save,One To Many,我有EmployeeExample和Deptt作为实体 员工示例与部门的一对一关系 Dept与EmployeeExample 我想通过关系保存数据。我有dept实体对象,我想用它保存employeeexampleentity 我做到了这一点,但我想知道这是否是最佳的方式。有什么好办法吗?我想知道这种关系是如何运作的 我的代码: import UIKit import CoreData class ViewController: UIViewController { var contain
EmployeeExample
和Deptt
作为实体
员工示例
与部门的一对一关系
Dept
与EmployeeExample
employeeexample
entityimport UIKit
import CoreData
class ViewController: UIViewController {
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var empSet = NSSet()
var empS = Set<EmployeeExample>()
override func viewDidLoad() {
super.viewDidLoad()
var context:NSManagedObjectContext = (container?.viewContext)!
let dept = NSEntityDescription.insertNewObject(forEntityName: "Deptt", into: context) as! Deptt
let emp = NSEntityDescription.insertNewObject(forEntityName: "EmployeeExample", into: (container?.viewContext)!) as! EmployeeExample
emp.firstName = "YYYY"
emp.lastName = "HHHHHHH"
empS.insert(emp)
print("Count of Emp SSSS Set == \(empS.count)")
let emp1 = NSEntityDescription.insertNewObject(forEntityName: "EmployeeExample", into: (container?.viewContext)!) as! EmployeeExample
emp1.firstName = "RRRRR"
emp1.lastName = "YYYYY"
empS.insert(emp1)
empSet.addingObjects(from: empS)
dept.deptName = "CCC"
print("Count of Emp SSSS Set == \(empS.count)")
print("Count of Emp Set == \(empSet.count)")
dept.addToEmp(empSet)
do {
try appDelegate.saveContext()
print("Saved -------------")
}catch {}
}
}
导入UIKit
导入CoreData
类ViewController:UIViewController{
var容器:NSPersistentContainer?=(UIApplication.shared.delegate作为?AppDelegate)?.persistentContainer
让appDelegate=UIApplication.shared.delegate为!appDelegate
var empSet=NSSet()
var empS=Set()
重写func viewDidLoad(){
super.viewDidLoad()
变量上下文:NSManagedObjectContext=(容器?.viewContext)!
让dept=NSEntityDescription.insertNewObject(forEntityName:“Deptt”,into:context)作为!Deptt
让emp=NSEntityDescription.insertNewObject(forEntityName:“EmployeeExample”插入:(container?.viewContext)!)作为!EmployeeExample
emp.firstName=“YYYY”
emp.lastName=“hhhhh”
emp.插入(emp)
打印(“Emp SSSS集合的计数=\(Emp.Count)”)
让emp1=NSEntityDescription.insertNewObject(forEntityName:“EmployeeExample”插入:(container?.viewContext)!)作为!EmployeeExample
emp1.firstName=“RRRRR”
emp1.lastName=“YYYYY”
环境管理计划插入(环境管理计划1)
empSet.addingObjects(from:empS)
部门名称=“CCC”
打印(“Emp SSSS集合的计数=\(Emp.Count)”)
打印(“Emp集合的计数=\(empSet.Count)”)
部门地址(empSet)
做{
请尝试appDelegate.saveContext()
打印(“已保存----------------”)
}捕获{}
}
}
我是否每次都必须创建一个Employee
实例
我是否每次都必须创建一个Employee
实例
你每次都有新员工吗?如果您有新信息,则需要创建新的员工
记录。如果您使用的是现有信息,则可以使用NSFetchRequest
从持久存储中查找现有的员工。当有新数据要保存时,可以创建新实例。你是否需要这样做只有你自己能回答。如果你有新的数据,是的。否则,不会