Search code examples
swiftrealm

Initialize Realm object without data in Swift


So suppose I have a Dog object that contains a reference to a Toy object:

class Dog: Object {

  dynamic var toy: Toy!

  convenience init(toyId: String) {
    self.init()

    let realm = try! Realm()
    toy = realm.object(ofType: Toy.self, forPrimaryKey: toyId)
  }
}

In this example, suppose I have a bunch of toys that have already been created in Realm, and I want to create a new instance of a dog and all I have is the toy id (not the actual toy object).

In the example above, I can make this work by doing a lookup for the toy, but if I'm creating a bunch of dogs all at once, this seems inefficient.

The other option, I suppose, is to fetch all the toys upfront and then pass the actual toy object to the dog initializer.

My question is, if I'm just trying to create a new dog, and link it to an existing toy, can that be done without having to fetch the toy?

I'm new to Realm, but when I was using Parse in the past they had a special initializer for this kind of scenario:

PFObject(withoutDataWithClassName: <String>, objectId: <String?>)

The idea was you could reference an object from the primary key, and only fetch the data if you end up needing it. Something like that, it seems, would be ideal for what I'm trying to do.


Solution

  • My question is, if I'm just trying to create a new dog, and link it to an existing toy, can that be done without having to fetch the toy?

    It is necessary to fetch the toy to establish the relationship between it and the dog.

    It's worth noting that looking up an object by primary key does not result in any properties of that object being loaded into memory. The returned object is just a pointer to a specific object in the Realm file on disk. The object's properties are read into memory only when they're accessed.