我使用DispatchQueue.main.async在主线程上调用Realm,它会抛出错误:
Terminating app due to uncaught exception 'RLMException', reason:
'Realm accessed from incorrect thread.'
以下是代码:
func add(word: String, toList list: WordList, completion: @escaping ((_ success: Bool) -> (Void))) {
let listId = list.timestamp
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
guard let json = TranslationManager.shared.translateFrom(list.from, to: list.to, text: word, autocorrect: true) else {
DispatchQueue.main.async {
completion(false)
}
return
}
DispatchQueue.main.async {
let newWord = Word()
newWord.text = word
newWord.timestamp = Int(Date().timeIntervalSince1970 * 1000)
newWord.json = json.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions()) ?? "{}"
newWord.translated = json[NativeJsonIndexes.translated].stringValue
let realm = try! Realm()
let currentRealmList = realm.objects(WordList.self).filter({
record in
return listId == record.timestamp
}).first
try! realm.write {
realm.add(newWord)
currentRealmList?.words.append(newWord)
}
}
}
}
我不明白为什么它可能会错误地工作,因为所有Realm交互都发生在主线程中,并且唯一的外部对象是使用ThreadSafeReference类传递的