2016-07-14 31 views
1

我有这个代码来搜索不同的表,我的问题是,我不能与用户界面进行交互,直到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) 
       } 
      } 
     } 
    } 
} 
+0

你为什么不首先加载5-10内容和实施拉刷新和增加5-10个新记录。 – gurmandeep

+0

大多数搜索结果不到10个,我不想让用户刷新并等待加载2个或大概0个记录。 – cubick84

+0

然后使用 dispatch_async(dispatch_get_main_queue(){ }) – gurmandeep

回答

0

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

对主线程异步运行的代码:

dispatch_async(dispatch_get_main_queue(), { 

    // RUN CODE OVER HERE 

}) 
+0

我的主要过程是在不同线程(“managedContext.performBlock”)中提取和运行,您提供给我的代码是访问主线程并更新UI。 – cubick84