Search code examples
iosswiftxcoderealmrealm-object-server

How can I access Realm database from a different ViewController?


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!


Solution

  • The database can be accessed anywhere with

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