Search code examples
swiftrealm

How to access results from a realm in swift


How do I access objects stored in realm?

I have a realm class "SubscriptionClass":

class SubscriptionClass: Object {
   @Persisted(primaryKey: true) var _id: ObjectId //the primary key
   @Persisted var subscription_number = 0
   @Persisted var question: String = ""
   @Persisted var option1: String = ""

with 2 instances:

let sub1 = SubscriptionClass()
sub1.subscription_number = 1  //<- the subscription number
sub1.question = "What is 3 * 3"
sub1.option1 = "9"

let sub2 = SubscriptionClass()
sub1.subscription_number = 2
sub1.question = "What is 5 * 5"
sub1.option1 = "25"

let realm = try! Realm()
realm.write {
   realm.add(sub1)
   realm.add(sub2)
}

I can get the results of the main SubscriptionClass:

let gplSubclassResults = realm.objects(SubscriptionClass.self)

However, how do I access the results of either sub1 or sub2?


Solution

  • You can retrieve specific SubscriptionClass by providing it's id which is used as primary key.

    realm.object(ofType: SubscriptionClass.self, forPrimaryKey: id)