我尝试在大型核心数据库中创建搜索(32,000个对象),但是当我向UISearchBar
添加一些文本时,我有一些滞后(因为我的基础是用新的搜索谓词更新)如何解决这个问题?如何在后台线程中更新我的基础?
fetchedResultController代码
lazy var context: NSManagedObjectContext = {
let appDelegate = (UIApplication.shared.delegate as? AppDelegate)
let context = appDelegate!.managedObjectContext
return context//appDelegate!.managedObjectContext
}()
lazy var fetchedResultsController: NSFetchedResultsController<CardsBaseClass> = {
let fetchRequest = NSFetchRequest<CardsBaseClass>(entityName: "CardsBase")
let sortDescriptor = NSSortDescriptor(key: "cardName", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate = nil
fetchRequest.fetchBatchSize = 50
fetchRequest.returnsObjectsAsFaults = false
//let mainContext = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
并添加一些子MOC以搜索方法
lazy var searchMOC: NSManagedObjectContext = {
let moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
moc.parent = self.context
return moc
}()
用于连接fetchedResultController我使用
override func viewDidAppear(_ animated: Bool) {
self.view.gestureRecognizers?.removeAll()
connectFetchedRequest()
}
func connectFetchedRequest() {
indicatorLoad.startAnimating()
context.perform({
do {
try self.fetchedResultsController.performFetch()
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
self.indicatorLoad.stopAnimating()
})
} catch {
print(error)
}
})
}
搜索谓词更新时使用以下代码
searchMOC.performAndWait({
if searchText != "" {
let predicate = NSPredicate(format: "\(self.searchPredicateName) contains[c] %@", searchText)
predicateArray.append(predicate)
}
self.fetchedResultsController.fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicateArray)
do {
try self.fetchedResultsController.performFetch()
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
} catch {
print(error)
}
})
我是否正确使用searchMOC.perform并通过DispatchQueue更新tableView? 我在核心数据实体中用于Predicates的所有属性都被“编入索引”,但在添加搜索文本时仍然存在很多滞后
答案 0 :(得分:0)
您必须获取子上下文,而不是主要上下文获取结果控制器。无论你在FRC中做什么都在主线程上,但你想要一个后台搜索。