插入数据时如何将项目连接到一对多关系中的类别

时间:2017-12-24 20:34:19

标签: ios core-data swift3

我有两个实体,一个客户,另一个是案例,关系是一对多,一个客户有很多案例,关系名称为客户实体和客户实体,所以在我的代码我通过segue传递选定的客户名称添加案例UIViewController

var CustmerNameForAddNewCaseVar: Customers?
CustomerNameLbl.text = CustmerNameForAddNewCaseVar?.name 

保存按钮

let newCase : Cases!
    newCase = Cases(context:context)
    newCase.caseName = caseNameTextField.text
    newCase.toCustomers = CustmerNameForAddNewCaseVar?.name // here i got error ... Cannot assign value of type 'String?' to type 'Customers?'
    do{
        AppDel.saveContext()
}catch{
        print(error)
    }

任何帮助 谢谢

1 个答案:

答案 0 :(得分:0)

要使用您的示例...您将更改您的代码以符合此:

let newCase : Cases!
newCase = Cases(context:context)
newCase.caseName = caseNameTextField.text
newCase.toCustomers = CustmerNameForAddNewCaseVar
do {
    // Save Context
} catch {
    // Handle Error
}

请注意“newCase.toCustomers”行已更改。

其他人在您的问题评论中建议的是清理实体和变量的命名,以帮助澄清用法。一个例子是:

import UIKit
import CoreData

class Customer: NSManagedObject {
    @NSManaged var cases: Set<Case>?
}

class Case: NSManagedObject {
    @NSManaged var customer: Customer?
    @NSManaged var name: String?
}

class ViewController: UIViewController {

    var customer: Customer?
    var context: NSManagedObjectContext?

    @IBOutlet weak var caseName: UITextField?

    @IBAction func didTapSave(_ sender: UIButton) {
        guard let context = self.context else {
            return
        }

        guard let customer = self.customer else {
            return
        }

        let newCase = Case(context: context)
        newCase.name = caseName?.text
        newCase.customer = customer

        do {
            try context.save()
        } catch {
            // Handle Error
        }
    }
}