I'm doing some background processing in an app with core data. The background processing is done on a child managedObjectContext. Context initialization:
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// the moc in appDelegate is created with .MainQueueConcurrencyType
mainThreadMOC = appDelegate.managedObjectContext!
backgroundMOC = NSManagedObjectContext(concurrencyType:NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
backgroundMOC?.parentContext = mainThreadMOC
Background processing is done in the following method:
// download all new transaction log entries
func syncItems() {
... set up the query object for parse
let moc = CoreDataStore.sharedInstance.backgroundMOC
// perform download
moc?.performBlock( {
self.runQuery(query) // Download stuff und do some core data work
})
}
The debugger shows that all work inside the block is indeed in a background thread.
When I call this function from the main thread and immediately block the main thread (for test purpose) with a lengthy core data operation, I see that the background thread stops and only continues execution when the main thread is idle.
// this is called from a view controller in the main thread
syncItems() // should start to work in background
for i in 0...200 {
// do some core data work in main thread
}
// syncItems starts to work after the blocking for-loop ends.
Why is that happening?