skip to Main Content

I have a class DataEntry that I want to store instances of in a Realm database, but i’m having issue instantiating a Realm. Here is my DataEntry class:

class DataEntry: Object {
    @objc dynamic var id = 0
    @objc dynamic var exercise = ""
    @objc dynamic var weightLBS = 0
    @objc dynamic var averageBarSpeed = 0
    @objc dynamic var topBarSpeed = 0

}

Some context as to what I’ll be using it for:
I’d like to have functions to write and delete instances of a DataEntry, but the documentation on that seems fairly simple.

  • Adding new dataEntry would be done by a user inputing data into a form
  • Deleting dataEntrys will simply be a button
  • Planning on reading the data to create graphs to track performance over time

The issue I’m having is instantiating a new Realm, and using the appropriate error handling. I’ve found a few simpler examples, but they all throw errors so i’m assuming there’s something i’m missing. I know you’re not supposed to use try!, so I’m wondering, what is a simple way to instantiate a new Realm, so I can then read/write/delete DataEntry’s to the Realm Database.

This one gives me multiple "Expected Declaration" errors in lines 1 and 3.

do {
      let realm = try Realm()
    } catch let error as NSError {
      // handle error
    }

This one gives me an "Expected Declaration" error on line 1

try {
    let realm = try Realm()
    } catch {
    print(error.localizedDescription)
    }

Any additional pointers on how to best set up this would be amazing, wether or not I should have a RealmManager class that would aid in error handling. I’ve seen in some cases people create extensions of Realm, but this is a little too advanced for me right now.

Background in CS, but brand new to both Swift and Realm for context.

Edit/Update:

Quick clarification, I’m having issues with instantiating a Realm. Not a Realm object. I’ve updated above to be more clear.

To clarify my question, I’m getting errors for what appears to be good code above, so I assume I have it in the wrong place. I get errors when its inside the DataEntry class, when its inside of a view, and at the top level of a SwiftUI file. Any advice on where I should include the c ode for the instantiation would be great!

2

Answers


  1. I am not sure if this will help but knowing where to put things within a project can sometimes help understand the flow.

    So I created a realm project in XCode that writes a person object with the name of Jay to realm when button 0 is clicked. Then when button 1 is clicked, it retrieves that data and prints to console.

    There’s no error checking here and I am force unwrapping an optional so don’t do that in a real app.

    import Cocoa
    import RealmSwift
    
    class PersonClass: Object {
        @Persisted var name = ""
    }
    
    class ViewController: NSViewController {
    
        @IBAction func button0Action(_ sender: Any) {
            let realm = try! Realm()
    
            let jay = PersonClass()
            jay.name = "Jay"
            try! realm.write {
                realm.add(jay)
            }
        }
    
        @IBAction func button1Action(_ sender: Any) {
            let realm = try! Realm()
            let jay = realm.objects(PersonClass.self).where { $0.name == "Jay" }.first!
            print(jay.name)  //outputs "Jay" to console
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }
    

    The project starts with importing RealmSwift and then the Realm object(s) are defined outside of any other classes, so they are at a high level.

    Then we have the ViewController with two button actions – as you can see, within each action function, we access realm with

    let realm = try! Realm()
    

    and then interact with realm. When that function exits, the realm object is deallocated so it’s a safe way to work with Realm and not leave it ‘connected’.

    Some developers create a singleton or a RealmService class to interact with Realm but singletons can be tricky. I suggest initially going with the pattern shown above (and in the docs).

    Login or Signup to reply.
  2. there has a better way to update and append a new record to Realm in the latest version.

    @ObservedResults(Group.self) var groups
    $groups.append(Group())
    TextField("New name", text: $item.name)
    

    The documentation is here, please take some time to read it.
    If it is hard for you, I suggest at least finishing this video by code along with her. LINK

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search