listswiftuirealmrelationship

RealmSwift: Appending List in One-to-many-Relationship


There are the two following classes with an One-to-many-Relationship between in my App:

class Lesson: Object, Identifiable {
   @Persisted(primaryKey: true) var id: ObjectId
   @Persisted var name: String
   @Persisted var pupils: List<Pupil>
}

class Pupil: Object, Identifiable {
   @Persisted(primaryKey: true) var id: ObjectId
   @Persisted var firstname: String
   @Persisted var lastname: String
   @Persisted(originProperty: "pupils") var lesson: LinkingObjects<Lesson>
}

I've implemented a view with a list of all existing lessons. It's possible to add new lessons and to delete them again. Each of the lessons is a NavigationLink to another view where all pupils of the selected lesson should be listed. There's a sheet (as separate view) for adding new pupils to this list, too. The action of the "Save-Button" in this view is the following:

.toolbar {
   ToolbarItem(placement: .confirmationAction) {
      Button("Save") {
         let newPupil = Pupil()
         newPupil.lastname = self.lastname
         newPupil.firstname = self.firstname
                
         try? realmService.localRealm.write {
            selectedLesson.pupils.append(neuerSchueler)
         }
         showModal = false
      }
   }
}

The selectedLesson is the lesson-object the new pupil should be added.

But there's the following error (a lot of lines following):

*** Terminating app due to uncaught exception 'RLMException', reason: 'Cannot modify List outside of a write transaction.'

I've tried some other variants as well. For example:

 let newPupil = Pupil()
 newPupil.lastname = self.lastname
 newPupil.firstname = self.firstname
                
 try? realmService.localRealm.write {
    selectedLesson.pupils.append(newPupil)
    realmService.localRealm.add(selectedPupil, update: Realm.UpdatePolicy.all)
 }

But the error is the same.

Can you help me, please. Thanks in advance!


Solution

  • If you are using @ObservedRealmObject or @ObservedResults

    Try something like

       $selectedLesson.pupils.append(neuerSchueler)
    

    Instead of the write operation

    https://www.mongodb.com/docs/realm-sdks/swift/latest/index.html

    https://www.mongodb.com/docs/atlas/device-sdks/sdk/swift/swiftui-tutorial/