如何使用带有NSPredicate的NSFetchedResultsController从UITableView中删除行?

时间:2013-05-06 07:01:35

标签: uitableview nspredicate nsfetchedresultscontroller

ViewController使用NSFetchedResultsController显示UITableView以访问Core Data(SQLite)。用户可以滑动和删除,显示添加的项目。一切都如预期。

UISearchBar用于过滤行时,它会用新实例替换NSFetchedResultsController。除了表示用户输入的NSPredicate设置为NSFetchRequest

之外,相同

在用户滑动删除行之前,所有功能仍然良好。引发commitEditingStyle并删除对象。引发didChangeObject并执行deleteRowsAtIndexPaths方法,但这次不删除该行。

事情开始变得梨形。如果用户再次尝试删除行,则会抛出

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' ***

因此tableView认为该索引上没有对象,但它是可见的,否则用户将无法引发commitEditingStyle方法。

如何让deleteRowsAtIndexPaths直观删除该行?

谢谢Rob

- (void) tableView:(UITableView *) tableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath *) indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        NSManagedObject *objectToDelete = [fetchedResultsController objectAtIndexPath:indexPath];
        [moc deleteObject:objectToDelete];
        [moc save:nil];
        [self saveData];

    }
}


- (void) saveData
{
    NSError *error = nil;
    [moc save:&error];
    if(kGlobalRunLogging && error) 
        NSLog(@"Failed to save data") ;
}

- (void) controller:(NSFetchedResultsController *) controller didChangeObject:(id) anObject
   atIndexPath:(NSIndexPath *) indexPath forChangeType:(NSFetchedResultsChangeType) type newIndexPath:(NSIndexPath *) newIndexPath 
{

    switch(type) {

        case NSFetchedResultsChangeUpdate:
            //Boring cell formatting stuff
            break;

        case NSFetchedResultsChangeDelete:
             [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
             break;

     }
 }

最后返回NSFetchedResultsController的方法

 - (NSFetchedResultsController *) fetchedResultsControllerWithPredicate:(NSPredicate *) aPredicate 
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Product" inManagedObjectContext:moc]];

    [request setPredicate:aPredicate];

    NSSortDescriptor *namesDescriptor = [[NSSortDescriptor alloc] initWithKey:@"initial" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:namesDescriptor, nil]];

    NSString *cacheName = @"Root";
    if(aPredicate) cacheName = nil;

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:@"initial" cacheName:cacheName];

    aFetchedResultsController.delegate = self;

    NSError *anyError = nil;
    if (![aFetchedResultsController performFetch:&anyError]) {
        NSLog(@"Error fetching: %@", anyError) ;
    }

    return aFetchedResultsController;

 }

0 个答案:

没有答案