gpt4 book ai didi

ios - Realm 将 List<> 对象添加到现有对象

转载 作者:行者123 更新时间:2023-11-28 19:25:24 25 4
gpt4 key购买 nike

这是我的 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;
}
);
}
);
}]

既然我已经创建了一项锻炼,那么我如何在不创建全新锻炼的情况下向该确切的锻炼添加新锻炼,所以我在该特定锻炼中注册了两个锻炼?

最佳答案

你想要:

  1. 获取现有的锻炼
  2. 创建一个新的练习
  3. 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
}

关于ios - Realm 将 List<> 对象添加到现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com