1

ViewController 显示UITableView使用 NSFetchedResultsController 访问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 直观地删除该行?

谢谢罗伯

- (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;

 }
4

0 回答 0