gpt4 book ai didi

iphone - 如何在 Realm Swift 中更新对象

转载 作者:行者123 更新时间:2023-12-03 18:18:37 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 Realm Swift 和 Charts,这样我最终就可以在我正在构建的应用程序中使用它们,并且我在弄清楚 Realm 上花了很多时间。最终,我计划让图表查看我的 Realm 数据库,然后根据数据显示图表,但在此之前,我需要检查 Realm 对象是否存在,如果不存在,创建它,然后当用户使用该应用程序时,向该记录添加“计数”并相应地更新图表。

随着我的学习,我已将其分解为多个步骤。我已经弄清楚如何检查记录是否存在,如果不存在则按如下方式构建:

我的 Realm 模型:

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)
}
}

我已通过 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")
}
}

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

Terminating app due to uncaught exception 'Invalid value', reason: 'Expected object of type date for property 'date' on object of type 'WorkoutsCount', but received: 2017-04-24 07:00:00 +0000'

最佳答案

更新对象只是为写入事务中的属性分配一个值。请参阅我们的文档。

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
}
}

仅供引用:请不要在查询中使用字符串插值。一般来说,通过字符串插值构建重要的字符串是不好的做法。使用 NSPredicate 的字符串替换语法,例如 filter("date = %@", removeTodaysItem)

关于iphone - 如何在 Realm Swift 中更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43622407/

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