Aggiungendo uno a molte relazioni in Swift
Domanda
Sono nuovo alla programmazione iOS e ho appena bisogno di un piccolo aiuto. Sto cercando di utilizzare i dati chiave e creare un semplice inserto dove c'è una nave da una per molte relazioni. La mia struttura di dati principali molto semplice è simile a questa
Ora nel codice ho creato anche Nsmmangedobject sottoclasse e sono in grado di creare questo oggetto singolarmente.Tutto ciò che ho bisogno di aiuto è come posso creare la relazione.Il mio codice è
XCode Generato Padre.Swift
class Father: NSManagedObject {
@NSManaged var name: String
@NSManaged var fatherToChild: NSSet
}
.
Xcode Generato Child.Swift
class Child: NSManagedObject {
@NSManaged var name: String
@NSManaged var child_father: NSManagedObject
}
.
Il mio metodo Aggiungi dati:
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)
}
. Soluzione
Tutto quello che devi fare è impostare la relazione da Bambino a Padre:
child1.child_father = newFather
child2.child_father = newFather
.
Aggiorna automaticamente la relazione (inversa) in newFather
.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow