How to update an object in real time

I am trying to learn how to use Realm Swift and Charts, so I can end up using them both in the application I am creating and in hell when I understand Realm. Ultimately, I plan that the diagrams look at my Realm database and then display the diagrams based on the data, but before I do this, I need to check if the realm object exists, if not, create it, and then when the user uses the application, adds “counts” to this entry and updates the schedule accordingly.

As I found out, I broke it into steps. I already understood how to check if a record exists, and if you don’t build it like this:

Model of my kingdom:

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

I checked that it works through the Realm Browser application.

Next, on my to-do list, I need to figure out how to update the entry for the “current date entry”. To do this, I created a button, so when she knocked, she will try to do it. I searched the web and searched on Google, and thought, since I am not using the primary key in my model, so I must first delete the specific record and then add it again with the new data. I can’t understand for my whole life how to do this, based on Kingdom documentation and even more of a search engine. This is what I have, although this does not work:

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

When I click the btnUpdate1MW button, I get the following error in Xcode:

Application termination due to an unreported exception "Invalid value", reason: "Expected date type object for the" date "property on the object of the" WorkoutsCount "type, but received: 2017-04-24 07:00:00 +0000

+7
iphone swift3 realm
source share
1 answer

Updating objects simply assigns a property value in a write transaction. See our documentation.

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

Therefore, you do not need to delete and then add the object. Just assign a new value to the property in the write transaction, as shown below.

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

FYI: Please do not use string interpolation in the query. Usually building an important line using line interpolation is bad practice. Use the NSPredicate string replacement syntax, for example filter("date = %@", removeTodaysItem) .

+20
source share

All Articles