我有一个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()
}
答案 0 :(得分:2)
您需要做两件事:
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;
}
答案 1 :(得分:0)
迅捷
这是您的原始谓词:
var predicate: NSPredicate {
return NSPredicate(format: "sampleCDAttribute == true")
}
文本过滤谓词:
var searchTextPredicate: NSPredicate {
let searchText = searchController.searchBar.text ?? ""
let andPredicate = NSPredicate(format: "text CONTAINS[cd] %@", searchText)
return NSCompoundPredicate(type: .and, subpredicates: [predicate, andPredicate])
}
NSFetchRequest 可能已包含在 FRC 工厂中,但已被提取以提高可读性:
var request: NSFetchRequest<ManagedWord> {
let request: NSFetchRequest<YourCDObject> = YourCDObject.fetchRequest()
request.predicate = predicate
request.sortDescriptors = [NSSortDescriptor(key: "text", ascending: true)]
return request
}
您的 FRC 声明:
//this is the container referencing from AppDelegate (customized)
var container: NSPersistentContainer = AppDelegate.persistentContainer
lazy var fetchedResultsController: NSFetchedResultsController<YourCDObject> = {
let frc = NSFetchedResultsController<YourCDObject>(
fetchRequest: request,
managedObjectContext: container.viewContext,
sectionNameKeyPath: "firstLetter",
cacheName: nil)
frc.delegate = self
return frc
}()
UISearchResultsUpdating 协议:
extension YourViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
do {
fetchedResultsController.fetchRequest.predicate = text.isEmpty ? predicate : searchTextPredicate
try fetchedResultsController.performFetch()
tableView.reloadData()
} catch {
print(error.localizedDescription)
}
}
}