I have a Realm object called Trip. It stores data of a user's movement.
class Trip: Object {
dynamic var id: Int = 0
dynamic var startTimestamp: Int64 = 0
dynamic var endTimestamp: Int64 = 0
dynamic var distance: Double = 0.0
dynamic var calories: Double = 0.0
dynamic var averageSpeed: Double = 0.0
}
In the view controller, I keep a class-level variable called trip.
fileprivate var trip: Trip?
Whenever a user starts a trip, I initialize a Trip object and assigns it to this variable.
trip = Trip()
And throughout the user's movements, I keep updating this trip object with the data.
I need to save this data to the Realm database every 1 minute. So I run a timer.
Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(save()), userInfo: nil, repeats: true)
Which executes a function to save this object in a background thread.
fileprivate func save() {
do {
DispatchQueue(label: "RealmBackgroundThread").async {
autoreleasepool {
let realm = try! Realm()
try! realm.write {
realm.add(self.trip!, update: true)
}
}
}
} catch {
}
}
Up to here, it works fine. The problem is after the first save, when I try to access that trip object again, it crashes with the following error.
libc++abi.dylib: terminating with uncaught exception of type realm::IncorrectThreadException: Realm accessed from incorrect thread.
I think this happens because I open a new Realm to save this object in a background thread. I know that Realm isn't thread-safe.
But I'm not sure how to resolve this. How do I keep using the same trip object after saving it?