写到上一个领域对象,而不是下一个

时间:2018-11-12 21:08:40

标签: ios swift object realm new-operator

我对Realm完全陌生,我正在尝试在数据库中添加一些数据。我的训练包括练习。每次培训都有ID,日期和练习列表。在我的表格视图中,我创建了两个训练,每个训练都有其自己的ID,此后,我在第一个训练中添加了一些练习,而当我尝试将其添加到第二个训练时,我得到了一个错误:“尝试创建类型为对象“ TrainingExercise”和现有的主键值“ Thruster”。”我不明白为什么要尝试将其添加到以前的培训中。我从数据库获取ID训练,然后检查是否将正确的ID传递给函数,仅此而已。但是当我设置断点时,训练的ID是先前的,我不明白其原因。有人可以帮我解决这个问题吗? 这是我的训练模型:

    class Training: Object {

    @objc dynamic var id = 0
    @objc dynamic var date = NSDate()
    var exercises = RealmSwift.List<TrainingExercise>()

    convenience init(date: NSDate, exercise: TrainingExercise) {
        self.init()
        self.date = date
        self.exercises.append(exercise)
    }

    override class func primaryKey() -> String? {
        return "id"
    }
}

这是我的锻炼模型:

 class TrainingExercise: Object {

    @objc dynamic var name: String = ""
    let sets = RealmSwift.List<GymSet>()


    convenience init(name: String, gymSet: GymSet) {
        self.init()
        self.name = name
        self.sets.append(gymSet)
    }

    override class func primaryKey() -> String? {
        return "name"
    }
}

class GymSet: Object {


    @objc dynamic var reps: Int = 0
    @objc dynamic var kilos: Double = 0
    @objc dynamic var time: String = ""

}

这是我用来在练习中添加练习的功能

func addExerciseForTraining(trainingId: Int, exercise: TrainingExercise) {

    let training = getTrainingById(id: trainingId)

    try? database.write {
        training.exercises.append(exercise)
    }

    try? database.write {
        database.create(Training.self, value: training, update: true)
    }

}


func getTrainingById(id: Int) -> Training {
    let training = database.object(ofType: Training.self, forPrimaryKey: id)

    return training!
}

1 个答案:

答案 0 :(得分:0)

您需要正确设置类之间的关系。因此,尝试像这样替换您的类:

class Training: Object {
    @objc dynamic var id = 0
    @objc dynamic var date = NSDate()
    var exercises = List<TrainingExercise>()
}

class TrainingExercise: Object {
    @objc dynamic var name: String = ""
    var training = LinkingObjects(fromType: Training.self, property: "exercises")
    var sets = List<GymSet>()
}

class GymSet: Object {
    @objc dynamic var reps: Int = 0
    @objc dynamic var kilos: Double = 0
    @objc dynamic var time: String = ""
    var exercise = LinkingObjects(fromType: TrainingExercise.self, property: "sets")
}

现在,当您想创建新文件时,就这样

let training = Training()

如果要更改其任何属性,请使用此示例

try? database.write {
    training.id = 1
}

并将培训添加到数据库中

try? database.write {
    database.add(training)
}