Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new Object to existing List in Realm

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

like image 404
PiterPan Avatar asked Jul 20 '16 20:07

PiterPan


2 Answers

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)
}
like image 64
bdash Avatar answered Oct 19 '22 04:10

bdash


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)
    }
}
like image 29
fs_tigre Avatar answered Oct 19 '22 02:10

fs_tigre