下面,我有 3 个与 CoreData 以不同方式在不同线程中获取对象相关的代码片段。其中一种方法是当我在从数据库中获取数据后尝试读取数据时 EXC_BAD_INSTRUCTION 崩溃,即使获取和读取是在同一线程上完成的。
QEventLoop
最后一个片段是导致问题的片段,而其他片段可以成功读取数据。
这就是我正在做的。
- 我创建了一个新的子上下文,其类型为 privateQueueConcurrencyType,父上下文设置为 mainContext
- 我首先使用此上下文使用 performAndWait 来获取和读取正常工作的数据。
- 然后我尝试使用 mainContext 在主线程中获取和读取。这也有效。
- 当我尝试在同一线程上使用子上下文获取并在没有执行块的情况下读取时,即使我在同一线程上它也会崩溃。
函数 print("hello: current thread is \(Thread.current)")
let moc = self.getchildmoc()
moc.performAndWait {
let contacts = PPContactSyncHelper.contactsIfExistsWith(connectIds: connectIds,moc: moc)
contacts.forEach { contact in
print("hello: 2. current thread is \(Thread.current)")
print("hello: \(contact.connectId)")
}
}
DispatchQueue.main.async {
let abContacts = PPContactSyncHelper.contactsIfExistsWith(connectIds: connectIds,moc: self.mainContext)
abContacts.forEach { abContact in
print("hello: \(abContact.connectId)")
}
}
let contacts = PPContactSyncHelper.contactsIfExistsWith(connectIds: connectIds,moc: moc)
contacts.forEach { contact in
print("hello: 2. current thread is \(Thread.current)")
print("hello: \(contact.connectId)")
}
使用提供的上下文从 performAndWait 块内的 coredata 中获取数据。
我在这里遗漏了什么?