How can I access Realm database from a different ViewController?

485 views Asked by At

I'm making an app (Swift 4), where a Realm database is created in one View Controller, but I cannot seem to access the objects from a different view controller. Essentially, a user rates a meal in the first view controller, and the meal name and a corresponding rating is stored as a Realm object to a database. I want to show a user a chart of the rated meals in a separate view controller (like a "Favourites" view controller), however I can't access the objects from that second view controller. How should I go about this? Thanks!

1

There are 1 answers

0
Shehata Gamal On BEST ANSWER

The database can be accessed anywhere with

do {
     let r = try Realm() 
     let stored = r.objects(ClassName.self)
     print(stored)
}
catch {
     print(error)
}