Hi, I am trying to write an application in Swift and using Realm. The application is something like a fitness tracker. Here is my data model:

class Meditation: Object { dynamic var name = "" dynamic var count = 0 dynamic var targetAmount = 0 dynamic var malasStep = 108 dynamic var id = 0 dynamic var imageName = "" dynamic var date = NSDate() override class func primaryKey() -> String? { return "id" } 

I need to display the number (count) and date in the statistics. That is for every day. For example 10/15/2016 - 200, 10/16/2016 - 100. But the amount (300) is saved in the database. And I can not display the amount for each day.

Prompt can somehow save everything into one entity, but so that each save of the count and date fields can be displayed.

  • Can I have an example code where you save / read records from a database? It feels like you have all the records saved in one, hence the amount - BrottyS

2 answers 2

Sori, did not immediately think to throw off. Here is one button

 @IBAction func add108(_ sender: UIButton) { totalCount += 108 countOfmeditationLabelUI.text = String(totalCount) try! realm.write { currentMeditation.count = totalCount currentMeditation.date = NSDate() realm.add(currentMeditation) } 

Here is the second

  @IBAction func addMore(_ sender: UIButton) { let alert = UIAlertController(title: "Add more", message: "Enter a count", preferredStyle: .alert) alert.addTextField { (textField) in } alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: {[weak alert] (_) in let textField = alert?.textFields?[0] self.totalCount += Int((textField?.text)!)! self.countOfmeditationLabelUI.text = String(self.totalCount) try! realm.write { self.currentMeditation.count = self.totalCount realm.add(self.currentMeditation) } })) 

And here is one of the 4 entities

 let med1 = Meditation() med1.name = "Refuge" med1.count = 0 med1.targetAmount = 111111 med1.malasStep = 108 med1.imageName = "refuge1.jpg" med1.id = 1 

    If I understood correctly, then the point is that you add the same self.currentMeditation object, so the database is updated, not added.

    To add a self.currentMeditation object, you must first create a new one:

     self.currentMeditation = Meditation() try! realm.write { self.currentMeditation.id = 1 self.currentMeditation.count = self.totalCount ... realm.add(self.currentMeditation) }