我有一个 NSFetchedResultsController
显示来自 Core Data 的一些数据,我正试图让一个搜索栏与它一起工作。搜索有效,但是调用 controller(didChangeObject:)
时使用的是全表的索引路径,而不是过滤后的表,因此更新要么修改了错误的记录,要么因为索引路径超出范围而导致错误。尽管我知道这是错误的根源,但我不确定如何修复它。我的代码的主要部分如下:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PlayerTableViewCell", forIndexPath: indexPath) as! PlayerTableViewCell
let coreDataIndexPath: NSIndexPath
if searchController.active && searchController.searchBar.text != "" {
coreDataIndexPath = fetchedResultsController.indexPathForObject(filteredPlayers[indexPath.row])!
} else {
coreDataIndexPath = indexPath
}
configureCell(cell, atIndexPath: coreDataIndexPath)
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Fetch Record
let record = fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
// Delete Record
managedObjectContext.deleteObject(record)
}
}
// MARK: Fetched Results Controller Delegate Methods
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch (type) {
case .Insert:
if let indexPath = newIndexPath {
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
case .Delete:
if let indexPath = indexPath {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
case .Update:
if let indexPath = indexPath {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! PlayerTableViewCell
configureCell(cell, atIndexPath: indexPath)
}
case .Move:
if let indexPath = indexPath {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
if let newIndexPath = newIndexPath {
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
}
}
}
// MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
if let searchText = searchController.searchBar.text {
let predicate = NSPredicate(format: "name CONTAINS %@", searchText)
if let fetchedObjects = fetchedResultsController.fetchedObjects as? [Player] {
filteredPlayers = fetchedObjects.filter({return predicate.evaluateWithObject($0)})
}
}
tableView.reloadData()
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredPlayers.count
} else if let sections = fetchedResultsController.sections {
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
return 0
}
configureCell
只是将 indexPath 处的记录中的数据加载到单元格中。
我之前曾尝试通过更改 fetchedResultsController.fetchRequest.predicate
进行搜索,但是当搜索栏被取消时,尽管我尽了最大努力,但表格不会恢复正常。该代码如下:
// MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = searchController.searchBar.text!
let predicate = NSPredicate(format: "%K CONTAINS[c] %@", argumentArray: ["name", searchText])
fetchedResultsController.fetchRequest.predicate = predicate
do {
try self.fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.userInfo)")
}
tableView.reloadData()
}
// MARK: UISearchBarDelegate
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
fetchedResultsController.fetchRequest.predicate = nil
do {
try self.fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.userInfo)")
}
tableView.reloadData()
}
最佳答案
这里有两件事你需要做:
- 在重新加载表数据之前,为
updateSearchResultsForSearchController
中的每个新搜索事件重置 NSFetchedResultsController; - 返回您的
cellForRowAtIndexPath
作为 FRC 中 indexPath 处的单元格。无需轮询 searchBar 的状态,NSFetchedResultsController 已经是最新的。
到目前为止我还不熟悉 Swift 语法,但它在 ObjC 中看起来像这样:
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
self.fetchedResultsController = nil;
[self.tableView reloadData];
}
-(NSFetchedResultsController *)fetchedResultsController{
if (_fetchedResultsController == nil) {
NSManagedObjectContext *context = self.managedObjectContext; // Creating FRC with main MOC
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSString *searchString = [self.searchController.searchBar.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@ ", searchString];
[fetchRequest setPredicate:predicate];
// Specify how the fetched objects should be sorted
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"someField" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
NSError *error = nil;
if (![_fetchedResultsController performFetch:&error])
NSLog(@"Error initializing FRC for Users. Error %@", error.userInfo);
_fetchedResultsController.delegate = self;
}
return _fetchedResultsController;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
MyEntity *myObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
/* Populate cell content here */
return cell;
}
关于ios - 我怎样才能使 NSFetchedResultsController Update 与 UISearchController 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675208/