Adding a new object to an existing list in the kingdom

I have two classes. At first it looks like this:

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

and a second class that looks like this:

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

and now in ViewControllerin 'viewDidLoad' I create an object Personwith an empty one Listand save it in Realm

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

It works fine, and I can create the Personproblem starts when I try to read this data in SecondViewControllerto ViewDidLoadby doing this:

var persons: Results<Person>?

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

and try adding a new one Dogin Listdoing this in the 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 application is broken with information: Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.How to add a new one Dogin Listand how can I update a person [0]? I am using SWIFT 3.0

+4
3

persons Results<Person>, , Person, Realm. , , .

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

- :

if let person = persons?[0] {
    person.dogs.append(newDog)
}

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

, , realm. , defaultRealm, .

+2

Side note. Besides adding code inside a write transaction that solves your problem, you can query Personby name, following ...

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

    let personName = realm.objects(Person.self).filter("name = 'Tomas'").first!

    try! realm.write {
        personName.dogs.append(newDog)
    }
}
0
source

Source: https://habr.com/ru/post/1648569/


All Articles