Below, I have 3 snippets of code related to CoreData fetching objects in different threads in different ways. One of these ways is crashing with EXC_BAD_INSTRUCTION when I am trying to read the data after fetching it from DB even though the fetching and reading is being done on the same thread.
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)")
}
The last snippet is the one that causes the issue while others can read the data successfully.
This is what I am doing.
- I create a new child context with type privateQueueConcurrencyType and parent set as mainContext
- I use this context first using performAndWait to fetch and read the data which works correctly.
- I then try to fetch and read in main thread using mainContext. That also works.
- When I try to fetch using the child context on the same thread and read without perform block, there it crashes even though I am on the same thread.
The function PPContactSyncHelper.contactsIfExistsWith fetches the data from coredata inside the performAndWait block using the context provided.
What am I missing here?