RealmSwift: How to create To-One Relationships properly?

Let's assume I have:

class Dog: Object {
    dynamic var race = ""
    dynamic var name = ""

    override static func primaryKey() -> String? {
        return "race"
    }
}

class Person: Object {
    dynamic var name = ""
    dynamic var address = ""
    dynamic var dog: Dog?

    override static func primaryKey() -> String? {
        return "name"
    }
}

First I create a Dog and save it:

let dog = Dog()
dog.race = "Dalmatian"

try! realm.write {
    realm.add(dog, update: true)
}

Now I create a Person in a different class. The docs are quite a bit unclear about this scenario. Do I need to save changes for the Dog first before creating the relationship?:

let person = Person()
person.name = "Jim"

// retrieve dog from realm: 

if let dog = realm.objectForPrimaryKey(Dog.self, key: "Dalmatian") {
    dog.name = "Rex" // Owner gives dog a new name

    // Question:
    // Saving changes to Rex: is this step neccessary?
    try! realm.write {
         realm.add(dog, update: true)
    }

    person.dog = dog
}

try! realm.write {
    realm.add(person, update: true)
}

Answers


No, and it will cause a crash

if let dog = realm.objectForPrimaryKey(Dog.self, key: "Dalmatian") {
    dog.name = "Rex" // Owner gives dog a new name

    person.dog = dog
}

if you want update the dog's name, write like this:

if let dog = realm.objectForPrimaryKey(Dog.self, key: "Dalmatian") {

        try! realm.write({ 
            dog.name = "Rex"
        })

        person.dog = dog

    }

see more: Realm.io/updating-objects


You can setup a whole object graph as unmanaged objects and persist them all by one call. So you don't need to persist the Dog first and retrieve it again to be able to use it in a relationship.

let dog = Dog()
dog.race = "Dalmatian"

let person = Person()
person.name = "Jim"
person.dog = dog

try! realm.write {
    realm.add(person, update: true)
}

Need Your Help

Desctuction of object is causing the crash of the program

c++ destructor

Here is a snippet of a considerably big C++ program:

PHP date.timezone not found with Docker & PHP-FPM

php docker docker-compose

I'm creating a Symfony environment (PHP-FPM, Nginx, & more) with Docker & Docker-compose.