如何从 swift 中的领域访问结果

How to access results from a realm in swift

如何访问存储在领域中的对象?

我有一个领域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 = ""

有 2 个实例:

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)
}

我可以获得主要 SubscriptionClass 的结果:

let gplSubclassResults = realm.objects(SubscriptionClass.self)

但是,如何访问 sub1 或 sub2 的结果?

您可以通过提供用作主键的 ID 来检索特定的 SubscriptionClass

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