Adding new Object to existing List in Realm

PiterPan picture PiterPan · Jul 20, 2016 · Viewed 12.6k times · Source

I have two classes. First looks like that:

class Person: Object {
    dynamic var owner: String?
    var dogs: List<Dogs>()
}

and second class which looks like that:

class Dogs: Object {
    dynamic var name: String?
    dynamic var age: String?
}

and now in ViewController in 'viewDidLoad' I create object Person with empty List and save it in Realm

func viewDidLoad(){
    let person = Person()
    person.name = "Tomas"
    try! realm.write {
        realm.add(Person.self)
    }
}

it works great and I can create Person, problem begins when I try to read this data in SecondViewController in ViewDidLoad doing it:

var persons: Results<Person>?

func viewDidLoad(){
    persons = try! realm.allObjects()
}

and try to add new Dog to List doing it in button action:

@IBAction func addDog(){
    let newDog = Dogs()
    newDog.name = "Rex"
    newDog.age = "2"

    persons[0].dogs.append(newDog)

    // in this place my application crashed

}

Here my app is crashing with an information: Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first. How can I add new Dog to List and how can I update person[0]? I use SWIFT 3.0

Answer

bdash picture bdash · Jul 20, 2016

The persons property is of type Results<Person>, which is a collection containing Person objects that are managed by a Realm. In order to modify a property of a managed object, such as appending a new element to a list property, you need to be within a write transaction.

try! realm.write {
    persons[0].dogs.append(newDog)
}