How do I filter a subclass in realm for swift?
I have a realm class "SubscriptionClass":
class SubscriptionClass: Object {
@Persisted(primaryKey: true) var subscriptionId = "" //the primary key
@Persisted var subscription_number = 0
@Persisted var question: String = ""
@Persisted var option1: String = ""
with 2 instances:
let sub1 = SubscriptionClass()
sub1.subscriptionId = "Grade 1" //<- the primary key
sub1.subscription_number = 1 //<- the subscription number
sub1.question = "What is 3 * 3"
sub1.option1 = "9"
let sub2 = SubscriptionClass()
sub2.subscriptionId = "Grade 2"
sub2.subscription_number = 2
sub2.question = "What is 5 * 5"
sub2.option1 = "25"
let realm = try! Realm()
realm.write {
realm.add(sub1)
realm.add(sub2)
}
To access main SubscriptionClass:
let allSubscriptionClassResults = realm.objects(SubscriptionClass.self)
To access the specific subclass:
let sub1ClassResults = realm.object(ofType: SubscriptionClass.self, forPrimaryKey: subscriptionId)
However, to make it more efficient, how do I filter for items in the subclass for example the question that is "What is 5*5"?
2
Answers
Search object by
primary_key
gives you only one specific object if it exists or it returnsnil
. And it’s time complexity in O(1).No filter option is more efficient than this. Because under the hood it works like look upon a dictionary and return the object it exists. In case of
filter
it works like iterating over the objects in the DB and return the matched objects.If you want to
filter
objects with other property which is notprimary_key
then it returns an array of objects which is already commented by @Larme. But it’s time complexity is O(n). Here is the codeIf there is only one object with a specific value of a property (not primary_key) then you can access the object using
filter
like below.There are actually multiple questions here. First we need to change the use of of the word
subclass
toinstance
. There are no subclasses in the question.Note that Realm is conceptually an `Object’ database so we’re going to use the word ‘object’ to refer the objects stored in Realm (the ‘instances’ when they’ve been loaded in to memory)
I will rephrase each for clarity:
and I will slide in #4: this queries for all questions as in #3 but only returns the very first one it finds. This can be dangerous because Realm objects are unordered so if there are ever more than one object, it could return a different first object each time it’s used
Subclass:
A subclass inherits the superclass’s functionality and extends it to provide additional functionality. Here’s a subclass that adds a difficulty property to a subclass of SubscriptionClass (the ‘super class’)
and then a different subclass that provides a subject property: