替换List <t>对象在Realm中不一致地持久化

时间:2016-06-01 00:59:52

标签: swift realm

我有一个偶然需要排序的List<Workout>对象(例如,如果用户不按顺序添加Workout),但我似乎无法获得新的排序List<Workout>坚持下去我的代码在它运行的那一刻起作用(即,它在视图中显示为已排序),但是当我退出ViewController或重新启动应用程序时,我什么也看不见。没有任何事情是由于exercise.workoutDiary.removeAll()持续存在,但显然随后对exercise.workoutDiary = sortedWorkoutDiary的分配并不持久。有什么想法吗?

其他一切都很好。典型的recordWorkout()案例假设没有按顺序输入任何内容。因此,除了覆盖已排序的List之外,持久化几乎在所有情况下都有效。

更新发生在这里:

struct ExerciseDetailViewModel {

    private let exercise: Exercise!

    func recordWorkout(newWorkout: Workout) {
        let lastWorkout = exercise.workoutDiary.last // grab the last workout for later comparison

        let realm = try! Realm()
        try! realm.write {
            exercise.workoutDiary.append(newWorkout) // write the workout no matter what
        }

        if let secondToLastWorkout = lastWorkout { // only bother checking out of order if there is a last workout...
            if newWorkout.date < secondToLastWorkout.date { // ...and now look to see if they are out of order
                let sortedWorkoutDiary = exercise.sortedWorkouts
                try! realm.write {
                    exercise.workoutDiary.removeAll()
                    exercise.workoutDiary = sortedWorkoutDiary
                }
            }
        }
    }
}

final class Exercise: Object {

    var workoutDiary = List<Workout>()
    var sortedWorkouts: List<Workout> {
        return List(workoutDiary.sorted("date"))
    }
}

final class Workout: Object {

    dynamic var date = NSDate()
    var sets = List<WorkSet>()
}

1 个答案:

答案 0 :(得分:4)

Realm Swift中的

List<T>属性必须在适当的位置进行变异,而不是分配给。 Swift运行时没有为Realm拦截通用类型属性的赋值提供任何方法。相反,您应该使用appendContentsOf(_:)之类的方法来改变List<T>

exercise.workoutDiary.removeAll()
exercise.workoutDiary.appendContentsOf(sortedWorkoutDiary)

对泛型类型属性的赋值限制是Realm Swift文档recommends that you declare such properties using let rather than var的原因。这将允许Swift编译器捕获这些错误。

还有一点需要注意:对于sortedWorkouts计算属性,最好返回Results<Workout>以避免分配和填充中间List<Workout>