ios - 核心数据: Access linked entity attributes

标签 ios swift core-data

我有一个名为“Expense”的实体,它链接到另一个名为“Trip”的实体。 我如何访问与每项费用相关的行程?

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 转换为 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/

相关文章:

ios - Swift 3 核心数据

ios - swift 4 : @IBOutlet UITextView crash

ios - 使用NSFetchedResultsController来获取对象的属性

objective-c - 如何从 NSDate 变量以及另一个 NSString 变量中生成字符串

ios - 如何在 UITableViewCell 中重用 UIView 的 xib 子类

SwiftUI 多屏导航

ios - 从值是字典数组的字典中获取值

ios - 3.2 带有占位符文本的应用程序将被拒绝

ios - 如何在 Core Data Swift 的关系中建立简单的连接

ios - 核心数据模型设计——反向关系