title: How to add and delete objects from a List from an object who's inside another List in SwiftUI and Realm
body: <p>In the following code I have a <code>List</code> of <code>Car</code>s and each <code>Car</code> from that list has its own list of <code>Service</code>s, I can add and delete <code>Car</code>s without a problem by calling <code>carViewModel.addNewCar(make:String, model:String)</code> and <code>carViewModel.deleteCar(at indexSet:IndexSet)</code>.</p>
  <h2>Car.swift</h2>
  <pre><code>    import RealmSwift
      final class Car: Object, ObjectKeyIdentifiable{
  
          @objc dynamic var make: String = &quot;&quot;
          @objc dynamic var model: String = &quot;&quot;
          // creation date, ID etc.
          dynamic var services = List&lt;CarService&gt;()
      }
  </code></pre>
  <h2>CarList.swift</h2>
  <pre><code>    import RealmSwift
  
      final class CarList: Object, ObjectKeyIdentifiable{
          
          @objc dynamic var name: String = &quot;&quot;
          // creation date, ID etc.
          var cars = RealmSwift.List&lt;Car&gt;()
      }
  </code></pre>
  <h2>CarService.swift</h2>
  <pre><code>    import RealmSwift
  
      final class CarService: Object, ObjectKeyIdentifiable{
  
          @objc dynamic var serviceName: String = &quot;&quot;
          // creation date, ID etc.
      }
  </code></pre>
  <h2>View Model</h2>
  <pre><code>    import RealmSwift
  
      class CarViewModel: ObservableObject{
          @Published var cars = List&lt;Car&gt;()
          @Published var selectedCarList: CarList? = nil
  
          var token: NotificationToken? = nil
          
          init(){
              // Create a the default lists if they don't already exist.
              createDefaultCarList()
              createDefaultServiceList()
              
              // Initialize the SelectedCarList and the cars variables items from the Default Car List.
              if let list = realm?.objects(CarList.self).first{
                  self.selectedCarList = list
                  self.cars = list.cars
              }
              
              token = selectedCarList?.observe({ [unowned self] (changes) in
                  switch changes{
                  case .error(_): break
                  case.change(_, _):self.objectWillChange.send()
                  case.deleted: self.selectedCarList = nil
                  }
              })
          }
          
          func addNewCar(make:String, model:String){
              if let realm = selectedCarList?.realm{
                  try? realm.write{
                      let car = Car()
                      car.make = make
                      car.model = model
                      selectedCarList?.cars.append(car)
                  }
              }
          }
          
          func deleteCar(at indexSet:IndexSet){
              if let index = indexSet.first,
              let realm = cars[index].realm{
                  try? realm.write{
                      realm.delete(cars[index])
                  }
              }
          }
          
          func addService(toCar: Car, serviceName: String){
              try? realm?.write{
                  let service = CarService()
                  service.serviceName = serviceName
                  
                  toCar.services.append(service)
              }
          }
          
          /// Creates the Default Car List if it doesn't already exists otherwise just prints the error.
          func createDefaultCarList(){
              do {
                  if (realm?.objects(CarList.self).first) == nil{
                      try realm?.write({
                          let defaultList = CarList()
                          defaultList.name = &quot;Default Car List&quot;
                          realm?.add(defaultList)
                      })
                  }
              }catch let error{
                  print(error.localizedDescription)
              }
          }
          
          /// Creates the Default Serivice List if it doesn't already exists otherwise just prints the error.
          func createDefaultServiceList(){
              do {
                  if (realm?.objects(ServiceList.self).first) == nil{
                      try realm?.write({
                          let defaultList = ServiceList()
                          defaultList.listName = &quot;Default Service List&quot;
                          realm?.add(defaultList)
                      })
                  }
              }catch let error{
                  print(error.localizedDescription)
              }
          }
      }
  </code></pre>
  <p>My issue is adding or deleting <code>Service</code>s to existing <code>Car</code>s. When I call <code>carViewModel.addService(toCar: Car, serviceName: String)</code> I get the error below...</p>
  <h2>Calling the addService() method.</h2>
  <pre><code>    struct NewServiceFormView: View {
          @ObservedObject var carViewModel: CarViewModel
          @State var selectedCar:Car // pass from other cars view
          
          var body: some View {
              NavigationView {
              Form {
                  // fields
              }
              .navigationBarItems( trailing:Button(&quot;Save&quot;, action: addNewCar))
              }
          }
  
          func addNewCar(){
              carViewModel.addService(toCar: selectedCar, serviceName: &quot;Oil Change&quot;)
          }
      }
  </code></pre>
  <h2>Error</h2>
  <blockquote>
  <p>&quot;Cannot modify managed RLMArray outside of a write transaction.&quot;</p>
  </blockquote>
  <p>I can add new <code>Services</code> by explicitly selecting a <code>Car</code> from the <code>cars</code> list. I don't get any errors but the UI doesn't update; I don't see the newly added Service until the app is relaunched.</p>
  <p>No errors doing it this way but the UI doesn't update.</p>
  <pre><code>carViewModel.addService(toCar: carViewModel.cars[1], serviceName: &quot;Rotors&quot;)
  </code></pre>
  <p>How can I properly watch, delete and add <code>Service</code>s to existing <code>Car</code>s?</p>
  <p><strong>EDIT</strong>: Added the following code per <code>Mahan</code>'s request.</p>
  <h2>View to present the NewServiceFormView</h2>
  <pre><code>    struct CarServicesView: View {
          @State var selectedCar:Car // a car from parent view
          @ObservedObject var carViewModel: CarViewModel
          
          var body: some View {
              VStack{
  
                  List {
                      Section(header: Text(&quot;Services: \(selectedCar.services.count)&quot;)) {
                          ForEach(selectedCar.services) { service in
                          }
                      }
                  }
                  .listStyle(GroupedListStyle())
                  .toolbar {
                      ToolbarItem(placement: .navigationBarTrailing) {
                          Button(action: openNewServiceForm) {
                              Image(systemName: &quot;plus&quot;)
                          }
                      }
                  }
              }.sheet(isPresented: $newServiceFormIsPresented){
                  NewServiceFormView(carViewModel: carViewModel, selectedCar: selectedCar)
              }
          }
          
          func openNewServiceForm() {
          newServiceFormIsPresented.toggle()
          }
      }
  </code></pre>