如何更新realm swift中的对象

jam*_*n34 18 iphone realm swift3

我正在尝试学习如何使用Realm Swift和Charts,这样我最终可以在我正在构建的应用程序中使用它们,而且我有一段时间搞清楚Realm.最终我打算让Charts查看我的Realm DB,然后根据数据显示图表,但在我这样做之前,我需要检查一下领域对象是否存在,如果不存在,则需要创建然后当用户使用应用程序时,将"计数"添加到该记录并相应地更新图表.

在我学习的过程中,我已将其分解为步骤.我已经弄清楚如何检查是否存在记录,如果不是这样构建它:

我的境界模型:

class WorkoutsCount: Object{    
    dynamic var date: Date = Date()
    dynamic var count: Int = Int(0)
}

// function to check if this weeks days have been created in Realm DB yet and creates them if not
    let realm = try! Realm()
    lazy var workouts: Results<WorkoutsCount> = { self.realm.objects(WorkoutsCount.self)}()
    let startOfWeekDate = Date().startOfWeek(weekday: 1)
    let nextDay = 24 * 60 * 60

    // checks the DB to see if it contains the start of this week
    func searchForDB(findDate: Date) -> WorkoutsCount?{
        let predicate = NSPredicate(format: "date = %@", findDate as CVarArg)
        let dateObject = self.realm.objects(WorkoutsCount.self).filter(predicate).first

        if dateObject?.date == findDate{
            return dateObject
        }
        return nil
    }

    func setThisWeeksDays(){
        //if the beginning of this week doesn't exist in the DB then create each day with 0's as the count data
        if searchForDB(findDate: startOfWeekDate) == nil{
            try! realm.write() {

                let defaultWorkoutDates = [startOfWeekDate, startOfWeekDate + TimeInterval(nextDay), startOfWeekDate + TimeInterval(nextDay*2), startOfWeekDate + TimeInterval(nextDay*3), startOfWeekDate + TimeInterval(nextDay*4), startOfWeekDate + TimeInterval(nextDay*5), startOfWeekDate + TimeInterval(nextDay*6)]

                for workouts in defaultWorkoutDates {
                    let newWorkoutDate = WorkoutsCount()
                    newWorkoutDate.date = workouts
                    self.realm.add(newWorkoutDate)
                }
            }            
            workouts = realm.objects(WorkoutsCount.self)
        }
    }
Run Code Online (Sandbox Code Playgroud)

我通过Realm Browser应用验证了他的作品.

我的待办事项列表中的下一步是弄清楚如何更新"今日约会记录"的记录.要做到这一点,我已经创建了一个按钮,所以当点击它时会尝试这样做.我一直在谷歌搜索和谷歌搜索,并开始思考,因为我不在我的模型中使用主键,我必须首先删除有问题的特定记录,然后再次添加新数据.我不能为我的生活找出如何根据Realm文档和更多谷歌搜索来做到这一点.这就是我所拥有的,虽然它不起作用:

@IBAction func btnUpdate1MW(_ sender: Any) {
        if searchForDB(findDate: today) != nil{
            if plusOne <= 7{
                plusOne += 1
                CounterImage1MW.image = UIImage(named:  "1MWs-done-\(plusOne)")

                let realm:Realm = try! Realm()

                // deletes the original item prior to being updated and added back below
                let removeTodaysItem = today
                let workout = realm.objects(WorkoutsCount.self).filter("date = '\(removeTodaysItem)'")
                if workout.count > 0{
                    for date in workout{
                        try! realm.write {
                            realm.delete(date)
                        }
                    }
                }
                // adds back the item with an updated count
                do {
                    let realm = try Realm()
                    try realm.write {
                        realm.create(WorkoutsCount.self, value: ["date": today, "count": plusOne], update: false)
                    }
                } catch let error as NSError {
                    fatalError(error.localizedDescription)
                }
            }

            print("add to 1MW + 1")
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我点击btnUpdate1MW按钮时,我在Xcode中收到以下错误:

因未捕获的异常"无效值"而终止应用程序,原因:'对象类型为'WorkoutsCount'的属性'date'的预期对象,但已收到:2017-04-24 07:00:00 +0000'

kis*_*umi 48

更新对象只是为写入事务中的属性赋值.查看我们的文档.

https://realm.io/docs/swift/latest/#updating-objects

因此您不需要删除然后添加对象.只需在写入事务中为属性分配新值,如下所示.

let workouts = realm.objects(WorkoutsCount.self).filter("date = %@", removeTodaysItem)

let realm = try! Realm()
if let workout = workouts.first {
    try! realm.write {
        workout.date = today
        workout.count = plusOne
    }
}
Run Code Online (Sandbox Code Playgroud)

仅供参考:请不要在查询中使用字符串插值.通常通过字符串插值构造重要的字符串是不好的做法.使用NSPredicate的字符串替换语法filter("date = %@", removeTodaysItem).