我有一个名为“Expense”的实体,它链接到另一个名为“Trip”的实体。 我如何访问与每项费用相关的行程?
我正在使用 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 转换为 Expense,然后访问它的属性吗?
let e = expense as! Expense
e.trip.value(forKey: "name")
最佳答案
在模型编辑器中,您需要向两个模型添加关系及其逆关系(看起来您已经至少部分完成了)。
如果我猜对了您的模型,请在费用与行程(称为行程)上设置一对一关系。在“行程”与“费用”(可能称为“费用”)上设置一对多关系,并将其与您在“费用”(称为“行程”)上建立的关系相反。
然后,如果您的目标是 Swift,您可以访问每个 Expense
上的 trip
;例如...
var 费用 = 费用()
费用.行程//...
关于ios - 核心数据: Access linked entity attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611903/