Captain725
Captain725

Reputation: 73

How to dynamically create or delete a realm class in swift

When a user purchases a subscription they can download the data into Realm Class. Below we is a Realm for SubscriptionOne.

However, if they later purchase SubscriptionTwo, which has the same properties, how can I create this Realm Class so that data can be saved?


import Foundation
import RealmSwift

class SubscriptionOne: Object {
    
    @DocumentID var idd: String
    @objc dynamic var id: Int = 0
    @objc dynamic var question: String = ""
    @objc dynamic var option1: String = ""
    @objc dynamic var option2: String = ""
    @objc dynamic var option3: String = ""
    @objc dynamic var option4: String = ""
    @objc dynamic var answer: String = ""
    @objc dynamic var correct: Int = 0
        
    override static func primaryKey() -> String? {
        return "id"
    }
    
}


Upvotes: 0

Views: 426

Answers (1)

Jay
Jay

Reputation: 35648

Realm Class definitions cannot be dynamically created - nor should they be.

If you have multiple objects with the same properties, then you should create instances of the Subscription Class

For example this would be created at the top level of your app, similar to what's in your question:

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 = ""
   ...

and then within the app, create the instance

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

and then for the second subscription

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

and then add them to realm

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

I also suggest using the @Persisted syntax when defining your Realm Classes. There's a lot more info in the Getting Started Guide: Objects

Upvotes: 1

Related Questions