如何编写Realm嵌套对象?

时间:2016-03-26 05:53:38

标签: swift realm

我有这个领域结构:

class DateLog: Object {
    dynamic var date = NSDate()
    let workouts = List<WorkoutLog>()
    let activities = List<ActivityLog>()
}

class WorkoutLog: Object {
    dynamic var name = ""
    dynamic var value = 0
    dynamic var notes = ""
}

class ActivityLog: Object {
    dynamic var name = ""
    dynamic var value = 0
    dynamic var notes = ""
}

如何添加到领域DateLog&gt;锻炼日志数据? (DateLog的日期; WorkoutLog的名称,值,注释)?

我正在寻找的工作流程:

  1. 将新记录添加到日期日志(只是日期)
  2. 添加该日期的锻炼日志记录(包含所有详细信息)
  3. 为同一日期添加活动日志记录

1 个答案:

答案 0 :(得分:6)

只需在写入块内创建并将DateLog对象添加到Realm:

let realm = try! Realm()

try realm.write {
    var dateLog = DateLog()
    dateLog.date = NSDate()

    var workoutLog = WorkoutLog()
    workoutLog.name = "My Workout"
    workoutLog.value = 1
    workoutLog.notes = "my note"

    dateLog.workouts.append(workoutLog)

    realm.add(dateLog)
}