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
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)
}
                        Side Note: Besides adding the code inside the write transaction which solves your issue, you could query Person by name as follow...
@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)
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With