2017-10-06 102 views
0

我有一個名爲「費用」的實體,鏈接到另一個稱爲「旅行」的實體。 如何訪問與每項費用相關的旅程?核心數據:訪問鏈接的實體屬性

enter image description here

我與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") 
+0

你能提供你到目前爲止的代碼嗎? – carlos21

回答

0

在模型編輯器,你需要添加的關係及其逆於兩種機型(它看起來就像你至少部分完成)。

如果我正確地猜測你的模型,在費用上設置一對一的關係跳轉(稱之爲旅行)。在費用之旅(可能叫費用)上設置多對多關係,並將其與您在費用(稱爲旅行)上的關係設置爲反比。然後,如果你的目標是斯威夫特,你可以訪問trip每個Expense;例如...

var expense = Expense() expense.trip // ...

+0

我明白了。但是...如果我正在使用NSManagedObjects呢? (我在編輯問題) – gmoraleda

+0

@gmoraleda我的例子實際上是用NsManagaedObjects,只是實際的類型(例如Expense),而不是超類。在你更新的例子中,如果你知道你有一個費用,那麼*是的*你可以投它。 – greymouser

相關問題