Adding new Object to existing List in Realm
Solution 1
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)
}
Solution 2
Write something like this:
if let person = persons?[0] {
person.dogs.append(newDog)
}
try! realm.write {
realm.add(person, update: true)
}
Please check how are you getting realm
. Each time you call defaultRealm
, you are getting new realm.
Solution 3
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)
}
}
Related videos on Youtube
PiterPan
Updated on June 04, 2022Comments
-
PiterPan almost 2 years
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 objectPerson
with emptyList
and save it in Realmfunc 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 inSecondViewController
inViewDidLoad
doing it:var persons: Results<Person>? func viewDidLoad(){ persons = try! realm.allObjects() }
and try to add new
Dog
toList
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 newDog
toList
and how can I update person[0]? I use SWIFT 3.0