如何在 swift 中动态创建或删除领域 class
How to dynamically create or delete a realm class in swift
当用户购买订阅后,他们可以将数据下载到 Realm Class。下面我们是 SubscriptionOne 的 Realm。
但是,如果他们以后购买具有相同属性的 SubscriptionTwo,我该如何创建这个 Realm Class 以便保存数据?
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"
}
}
领域 Class 定义不能动态创建 - 也不应该。
如果您有多个具有相同属性的对象,那么您应该创建订阅实例 Class
例如,这将在您的应用程序的顶层创建,类似于您的问题:
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 = ""
...
然后在应用程序中创建实例
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)
}
我还建议在定义领域时使用@Persisted 语法Classes。 Getting Started Guide: Objects
中有更多信息
当用户购买订阅后,他们可以将数据下载到 Realm Class。下面我们是 SubscriptionOne 的 Realm。
但是,如果他们以后购买具有相同属性的 SubscriptionTwo,我该如何创建这个 Realm Class 以便保存数据?
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"
}
}
领域 Class 定义不能动态创建 - 也不应该。
如果您有多个具有相同属性的对象,那么您应该创建订阅实例 Class
例如,这将在您的应用程序的顶层创建,类似于您的问题:
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 = ""
...
然后在应用程序中创建实例
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)
}
我还建议在定义领域时使用@Persisted 语法Classes。 Getting Started Guide: Objects
中有更多信息