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)
}
任何帮助 谢谢
答案 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
}
}
}