领域添加列表反对已有的对象 [英] Realm add List<> object to already existing object
本文介绍了领域添加列表反对已有的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的Object
类的外观:
Workout.swift:
Workout.swift:
class Workout: Object {
@objc dynamic var date: Date?
// List of exercises (to-many relationship)
var exercises = List<Exercise>()
}
Exercise.swift
Exercise.swift
class Exercise: Object {
@objc dynamic var name: String?
// List of sets (to-many relationship)
var sets = List<Set>()
var parentWorkout = LinkingObjects(fromType: Workout.self, property: "exercises")
}
Set.swift
Set.swift
class Set: Object {
@objc dynamic var reps: Int = 0
@objc dynamic var kg: Double = 0.0
@objc dynamic var notes: String?
// Define an inverse relationship to be able to access your parent workout for a particular set (if needed)
var parentExercise = LinkingObjects(fromType: Exercise.self, property: "sets")
convenience init(numReps: Int, weight: Double, aNote: String) {
self.init()
self.reps = numReps
self.kg = weight
self.notes = aNote
}
}
我已经创建了一个锻炼:
And I have a workout that is already created:
[Workout {
date = 2019-12-07 23:26:48 +0000;
exercises = List<Exercise> <0x281ea5b00> (
[0] Exercise {
name = Barbell Biceps Curl;
sets = List<Set> <0x281eb0090> (
[0] Set {
reps = 10;
kg = 40;
notes = Light;
},
[1] Set {
reps = 10;
kg = 40;
notes = Light;
},
[2] Set {
reps = 12;
kg = 37.5;
notes = Hard;
}
);
}
);
}]
现在我已经创建了一个锻炼,如何在不创建全新锻炼的情况下向该精确锻炼添加新锻炼,所以我在该特定锻炼中注册了两个锻炼?
Now that I have a workout that has already been created, how can I add a new exercise to that exact workout, without creating a whole new workout, so I have two exercises registered in that specific workout?
推荐答案
您要:
- 获取现有的
Workout
- 创建一个新的
Exercise
- 将
Exercise
附加到Workout
- Fetch an existing
Workout
- Create a new
Exercise
- Append the
Exercise
to theWorkout
我假设您知道要获取的Workout
的主键pkey
.
I assume you know the primary key pkey
of the Workout
you want to fetch.
let myWorkout = realm.object(ofType: Workout.self, forPrimaryKey: pkey)! // 1: fetch an existing workout
let exercise = Exercise() // 2: create a new exercise with some sets
let set1 = Set(numReps: 1, weight: 1.0, aNote: "one")
let set2 = Set(numReps: 2, weight: 2.0, aNote: "two")
exercise.sets.append(objectsIn: [set1, set2])
try! realm.write {
myWorkout.exercises.append(exercise) // 3: append
}
这篇关于领域添加列表反对已有的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文