CoreData数据库操作关联操作
let des = NSEntityDescription.entity(forEntityName: "Student", in: self.getContext())
let student = NSManagedObject(entity: des!,insertInto: self.getContext())
student.setValue("张杰", forKey: "name")
student.setValue(12, forKey: "idCard")
let teDes = NSEntityDescription.entity(forEntityName: "Teacher", in: self.getContext())
let teacher = NSManagedObject(entity: teDes!,insertInto: self.getContext())
teacher.setValue("老王", forKey: "name")
teacher.setValue(32, forKey: "age")
let des1 = NSEntityDescription.entity(forEntityName: "Student", in: self.getContext())
let student1 = NSManagedObject(entity: des1!,insertInto: self.getContext())
student1.setValue("谢娜", forKey: "name")
student1.setValue(12, forKey: "idCard")
let teDes1 = NSEntityDescription.entity(forEntityName: "Teacher", in: self.getContext())
let teacher1 = NSManagedObject(entity: teDes1!,insertInto: self.getContext())
teacher1.setValue("老王1", forKey: "name")
teacher1.setValue(32, forKey: "age")
var set = Set<NSManagedObject>()
set.insert(student)
set.insert(student1)
teacher.setValue(set, forKey: "students")
var stSet = Set<NSManagedObject>()
stSet.insert(teacher)
stSet.insert(teacher1)
student.setValue(stSet, forKey: "teachers")
try! self.getContext().save()
print(NSTemporaryDirectory())
//查找teacher的学生都叫什么
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Teacher");
//查找
let pre = NSPredicate(format: "name = '老王'", argumentArray: nil)
request.predicate = pre
//执行查找
let arr = try! self.getContext().fetch(request) as![NSManagedObject]
for item in arr { //获取到每一个老师
let set = item.value(forKey: "students") as! Set<NSManagedObject>
for stu in set {
let name=stu.value(forKey: "name")as! String
print("老王的学生为名\(name)")
}
//删除
//self.getContext().delete(item)
}
try! self.getContext().save()
}
func getContext() -> NSManagedObjectContext {
let delegate=UIApplication.shared.delegate as! AppDelegate
let context=delegate.persistentContainer.viewContext
return context