Search code examples
iosswiftswift3realmcllocation

RealmSwift - begin/commit writes


In my fitness tracker app, I save current run and invoke reverse geolocation method, that is supposed to get the location name where run took place.

First I write 'latestRun' to realm, then I wait for the reverse geocoding to complete and try to modify 'latestRun' variable

try! realm.write {
        realm.add(latestRun)
    }

if !savedLocations.isEmpty
    {
         ReverseGeocoder.getPlace(latitude: savedLocations[0].latitude, longitude: savedLocations[0].longitude, completionHandler: {
            place in
            realm.beginWrite()
            try! realm.write {
                latestRun.place = place

            }
            try! realm.commitWrite()

        })
    }

it results with an exception

Terminating app due to uncaught exception 'RLMException', reason: 'The Realm is already in a write transaction'

What am I doing wrong? What I found in docs is that beginWrite() and commitWrite() methods should be used in this case.


Solution

  • No need to use neither commitWrite() nor beginWrite()

    try! realm.write {
       latestRun.place = place
     }
    

    is sufficient