UI挂起,直到完成所有提取

时间:2016-07-14 15:52:04

标签: ios swift user-interface core-data tableview

我有这个代码来搜索不同的表,我的问题是在执行las fetch请求之前我无法与UI交互。 如果我搜索特定值并且结果在“Table2”中,则tableView更新正常但在完成搜索最后一个表之前无法与其进行交互。 func loadData()只需要几毫秒来执行和退出,并且提取正在另一个线程中执行。我不知道这段代码有什么问题,有什么帮助或建议吗? 所有表中的记录总数大约为5百万,搜索所有表中需要一些时间,这就是为什么我不想让用户等待,如果在完成搜索整个数据库之前有一些结果可用。< / p>

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)
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

UI处理主线程中的大部分进程。如果您有一个主要流程,请不要同步在主线程上运行它。您可以在主线程上异步运行它。

在主线程上异步运行的代码:

dispatch_async(dispatch_get_main_queue(), {

    // RUN CODE OVER HERE

})
相关问题