I am trying to make an extension to support writing realm objects on a background thread. (I followed another realm doc tutorial.)
When you make a ThreadSafeReference
of an unmanaged object, it crashes. I solved that issue by added a condition to my block to changed if the object was managed, and write normally otherwise.
My issue arises in that I do most of my reads on the main thread. So, when I create a new object A
that has a property that references another object B
which happens to be managed, I cannot make a ThreadSafeReference, but it also crashes when trying to write because B
is “managed” by a different thread.
Any ideas?
private static func writeAsync<T: ThreadConfined>(object: T, block: @escaping (Realm, T) -> Void) {
if let realm = object.realm {
let wrappedObject = ThreadSafeReference(to: object)
backgroundQueue.async {
autoreleasepool {
let realm = try! Realm(configuration: realm.configuration)
let object = realm.resolve(wrappedObject)
guard let object = object else { return }
try! realm.write {
block(realm, object)
}
}
}
} else {
backgroundQueue.async {
let realm = try! Realm()
try! realm.write {
block(realm, object)
}
}
}
}