核心数据在大多数情况下都非常有效。当我单击第一个VC(项)的名称并对第二个VC(成本)执行performSeque时,我可以看到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)

}

最佳答案

我不知道您是否在某处执行此操作,但是您的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,但您了解原理)

关于ios - 一对多关系CoreData Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27877740/

10-12 01:46