One to Many Relationships CoreData Swift
Core Data works great for the most part. When I click on the name first VC (Items) and Seque on the second VC (Costs), I can see the costName and other data. But when I add the second name to the first VC, I can see the same data as on the name.
I am trying to make a relationship to each other.
I have 2 data models:
import Foundation
import CoreData
@objc(Items)
class Items: NSManagedObject {
@NSManaged var count: NSNumber
@NSManaged var name: String
@NSManaged var cost: NSSet
}
import Foundation
import CoreData
@objc(Costs)
class Costs: NSManagedObject {
@NSManaged var costsDate: NSDate
@NSManaged var costsName: String
@NSManaged var costsValue: NSNumber
@NSManaged var account: Items
}
Below is the action addAccount
(name of first VC):
@IBAction func saveButtonPressed(sender: UIBarButtonItem) {
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Items", inManagedObjectContext: managedObjectContext!)
let account = Items(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
account.name = cellOneNameTextField.text
if cellTwoCountTextField.text.isEmpty {
} else {
account.count = (cellTwoCountTextField.text).toInt()!
}
// Saving data
appDelegate.saveContext()
var request = NSFetchRequest(entityName: "Items")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
self.navigationController?.popViewControllerAnimated(true)
}
Here's the addCost
save action:
@IBAction func saveButtonTapped(sender: UIBarButtonItem) {
// CoreData Access
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Costs", inManagedObjectContext: managedObjectContext!)
let cost = Costs(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
cost.costsName = cellThreeNoteTextField.text
cost.costsValue = (cellOnePriceTextField.text).toInt()!
cost.costsDate = datePicker.date
// Saving data
appDelegate.saveContext()
var request = NSFetchRequest(entityName: "Costs")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
for res in results {
println(res)
}
delegate?.refreshTable()
self.navigationController?.popViewControllerAnimated(true)
}
source to share
I don't know if you will do this somewhere, but yours Items
should attach the object Count
to itself using your variable cost
from yours Items
. Something like:
let account = Items(...)
let cost = Cost(...)
account.cost.addObject(cost)//and changing your var cost:NSSet into var cost:NSMutableSet
//then save Items
(I haven't tried addObject, but you get the idea)
source to share