I am new to iOS programming and just need a small help. I am trying to use core data and create a simple insert where there is a one to many relation ship. My very simple core data structure looks like this
我是iOS编程的新手,只需要一点帮助。我正在尝试使用核心数据并创建一个简单的插入,其中存在一对多的关系。我非常简单的核心数据结构如下所示
Now in the code i have created NSManagedObject subclass as well and am able to create this objects individually. All i need help is how do i create the relationship. My code is is
现在在代码中我也创建了NSManagedObject子类,并且能够单独创建这些对象。我需要帮助的是如何创建关系。我的代码是
Xcode generated Father.swift
Xcode生成了Father.swift
class Father: NSManagedObject {
@NSManaged var name: String
@NSManaged var fatherToChild: NSSet
}
Xcode generated Child.swift
Xcode生成了Child.swift
class Child: NSManagedObject {
@NSManaged var name: String
@NSManaged var child_father: NSManagedObject
}
My Add Data method:
我的添加数据方法:
func addData(){
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
var fatherEntity = NSEntityDescription.entityForName("Father", inManagedObjectContext: context)
var newFather = Father(entity: fatherEntity, insertIntoManagedObjectContext: context)
newFather.name = "Daddy"
var childEntity = NSEntityDescription.entityForName("Child", inManagedObjectContext: context)
var child1 = Child(entity: childEntity, insertIntoManagedObjectContext: context)
child1.name = "child1"
var child2 = Child(entity: childEntity, insertIntoManagedObjectContext: context)
child2.name = "child2"
//How to map these 2 childs to father? Need help in code here!
context.save(nil)
}
1 个解决方案
#1
13
All you have to do is to set the relationship from Child to Father:
你所要做的就是设置从孩子到父亲的关系:
child1.child_father = newFather
child2.child_father = newFather
This automatically updates the (inverse) relationship in newFather
.
这会自动更新newFather中的(反向)关系。
#1
13
All you have to do is to set the relationship from Child to Father:
你所要做的就是设置从孩子到父亲的关系:
child1.child_father = newFather
child2.child_father = newFather
This automatically updates the (inverse) relationship in newFather
.
这会自动更新newFather中的(反向)关系。