核心数据:访问链接的实体属性
我有一个名为“费用”的实体,链接到另一个称为“旅行”的实体。 如何访问与每项费用相关的旅程?核心数据:访问链接的实体属性
我与NSManagedObjects工作,所以作为一个例子,我的方法这里之一:
func fillCellWithExpense(cell: DayExpensesViewCell, expense: NSManagedObject) -> DayExpensesViewCell {
let amount = expense.value(forKey: AMOUNT) as! Double
cell.amountLabel?.text = String(format:"%.2f", amount)
let category = expense.value(forKey: CATEGORY) as! String
cell.categoryLabel?.text = category
switch category {
case "Transportation":
cell.line.backgroundColor = Colors.C1
case "Shopping":
cell.line.backgroundColor = Colors.C2
case "Food":
cell.line.backgroundColor = Colors.C3
case "Accomodation":
cell.line.backgroundColor = Colors.C4
case "Fun":
cell.line.backgroundColor = Colors.C5
case "Coffee":
cell.line.backgroundColor = Colors.C6
case "Groceries":
cell.line.backgroundColor = Colors.C7
default:
cell.line.backgroundColor = Colors.C8
}
return cell
}
如果我想访问支出之旅的名字,我可以简单地把NSManagedObject费用,然后访问它的属性?
let e = expense as! Expense
e.trip.value(forKey: "name")
在模型编辑器,你需要添加的关系及其逆于两种机型(它看起来就像你至少部分完成)。
如果我正确地猜测你的模型,在费用上设置一对一的关系跳转(称之为旅行)。在费用之旅(可能叫费用)上设置多对多关系,并将其与您在费用(称为旅行)上的关系设置为反比。然后,如果你的目标是斯威夫特,你可以访问trip
每个Expense
;例如...
var expense = Expense() expense.trip // ...
我明白了。但是...如果我正在使用NSManagedObjects呢? (我在编辑问题) – gmoraleda
@gmoraleda我的例子实际上是用NsManagaedObjects,只是实际的类型(例如Expense),而不是超类。在你更新的例子中,如果你知道你有一个费用,那么*是的*你可以投它。 – greymouser
你能提供你到目前为止的代码吗? – carlos21