【发布时间】:2015-04-27 15:41:54
【问题描述】:
我正在使用核心数据的应用程序中进行一些后台处理。后台处理在子 managedObjectContext 上完成。上下文初始化:
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
后台处理方式如下:
// 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
})
}
调试器显示块内的所有工作确实都在后台线程中。
当我从主线程调用此函数并立即使用冗长的核心数据操作阻塞主线程(用于测试目的)时,我看到后台线程停止并且仅在主线程空闲时继续执行。
// 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.
为什么会这样?
【问题讨论】:
-
子上下文不适用于后台处理
标签: ios multithreading core-data nsmanagedobjectcontext