从主线程上的错误线程访问Swift 3域
我正在使用DispatchQueue.main.async调用主线程上的域,它抛出一个错误:从主线程上的错误线程访问Swift 3域,swift,multithreading,realm,Swift,Multithreading,Realm,我正在使用DispatchQueue.main.async调用主线程上的域,它抛出一个错误: Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.' 代码如下: func add(word: String, toList list: WordList, completion: @escaping ((_ success: Bool) -&
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)
}
}
}
}
我不明白为什么它可能工作不正确,因为所有领域交互都发生在主线程中,唯一的外部对象是使用ThreadSafeReference类传递的在哪一行提示错误?@LucaNicoletti xcode没有显示它,它显示了“}”上的错误我认为问题与ThreadSafeReference有关。ThreadSafe只保证变量不会同时从不同的线程访问:它不保证只有一个线程。试着评论一下你使用该引用的行,然后让我know@LucaNicoletti我尝试只传递一个Int-id并检索DispatchQueue.main.async块中的对象,然后返回错误stays@AndriiLiakh如果你做得对,传递一个id并检索对象肯定会起作用,你能分享一下你那次尝试的代码吗?此外,如果在调试器中设置了异常断点,则应该能够准确地看到是哪一行导致了问题。