我有這個代碼來搜索不同的表,我的問題是,我不能與用戶界面進行交互,直到las fetch請求被執行。 如果我搜索特定值並且結果在「Table2」中,那麼tableView會更新正常,但無法與其進行交互,直到完成搜索最後一個表爲止。 func loadData()只需要幾毫秒的時間來執行和退出,並且抓取正在另一個線程中執行。我不知道這段代碼有什麼問題,有什麼幫助或建議嗎? 所有表中的記錄總數約爲5百萬,需要一些時間來搜索所有表中的記錄,這就是爲什麼我不希望在用戶搜索完整個數據庫之前有一些結果可用的情況下等待。用戶界面掛起,直到完成所有提取
func loadData() {
let tablas = ["Table1", "Table2", "Table3", "Table4", "Table5", "Table6", "Table7", "Table8", "Table9", "Table10", "Table11"]
let managedContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
managedContext.parentContext = self.moc
for tbl in tablas {
managedContext.performBlock {
let fetchRequest = NSFetchRequest(entityName: tbl)
let predicate = NSPredicate(format: "name CONTAINS %@", self.filter)
fetchRequest.predicate = predicate
fetchRequest.resultType = NSFetchRequestResultType.ManagedObjectIDResultType
fetchRequest.fetchLimit = 50
fetchRequest.fetchBatchSize = 10
do {
let results = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObjectID]
if results.count != 0 {
self.resultArray.appendContentsOf(results)
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
} catch let error as NSError {
dispatch_async(dispatch_get_main_queue()) {
let errorAlert = UIAlertController(title: "Error!!!", message: error.localizedDescription, preferredStyle: .Alert)
errorAlert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(errorAlert, animated: true, completion: nil)
}
}
}
}
}
你爲什麼不首先加載5-10內容和實施拉刷新和增加5-10個新記錄。 – gurmandeep
大多數搜索結果不到10個,我不想讓用戶刷新並等待加載2個或大概0個記錄。 – cubick84
然後使用 dispatch_async(dispatch_get_main_queue(){ }) – gurmandeep