[英]Realm add List<> object to already existing object
這是我的Object
類的樣子:
鍛煉.swift:
class Workout: Object {
@objc dynamic var date: Date?
// List of exercises (to-many relationship)
var exercises = List<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")
}
設置.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
}
}
我有一個已經創建的鍛煉:
[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;
}
);
}
);
}]
既然我已經創建了一個鍛煉,我如何在不創建全新鍛煉的情況下向該確切鍛煉添加新鍛煉,因此我在該特定鍛煉中注冊了兩個鍛煉?
你想要:
Workout
Exercise
Exercise
附加到Workout
我假設您知道要獲取的Workout
的主鍵pkey
。
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
}
由於您的用戶每天只能登錄一次鍛煉,您可以按日期查找特定鍛煉:
if let workout = realm.objects(Workout.self).filter("date = %@", date).first {
// Workout found
try! realm.write {
workout.exercises.append(exerciseToAppend)
}
} else {
// Workout not found, handle it the way you want
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.