一对多关系Core Data Swift

时间:2015-01-10 15:18:08

标签: ios swift core-data

Core Data在大多数情况下都很有用。当我点击名字第一个VC(Items)并执行Seque到第二个VC(Costs)时,我可以看到costsName和其他数据。但是当我在第一个VC中添加第二个名字时,我可以看到与名字相同的数据。

我正试图建立一对多的关系。

我有2个数据模型:

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

}

以下是addAccount(第一个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)

}

以下是addCost的保存操作:

    @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)

}

1 个答案:

答案 0 :(得分:1)

我不知道您是否在某个地方执行此操作,但您的Items应使用Count中的cost变量将Items对象附加到自身。类似的东西:

let account = Items(...)     
let cost = Cost(...)   
account.cost.addObject(cost)//and changing your var cost:NSSet into var cost:NSMutableSet
//then save Items

(我没有尝试过addObject,但你理解了这个原理)