开发者

Whats wrong with this UITableView deletion code?

I am receiving the error below from the following code, please can you tell me what my problem is.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).'

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        id object = [[[self cdArray] objectAtIndex:indexPath.row] retain];
        [[self cdArray] removeObject:object];
        [[self managedObjectContext] deleteObject:object];
        [self refreshArray];
        NSError *error = nil;
        if (![[self managedObjectContext] save:&error]) {
            NSLog(@"\n%s\n%@", __PRETTY_FUNCTION__, [error description]);
        }
        [[self tableView] deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (void) refreshArray {
    if ([self cdArray] == nil) {
        [self setCdArray:[[NSMutableArray alloc] init]];
    }
    [cdArray removeAllObjects];
    NSFetchRe开发者_运维知识库quest *fetchRequest = [[NSFetchRequest alloc] init];
    NSError *error = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Image" 
                                              inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];    
    for (CDImage *image in fetchedObjects) {
        [cdArray addObject:image];
    }
    [[self tableView] reloadData];
    [fetchRequest release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}


You shouldn't call

[self refreshArray];

until after you have committed your delete here,

NSError *error = nil;
if (![[self managedObjectContext] save:&error]) {
    NSLog(@"\n%s\n%@", __PRETTY_FUNCTION__, [error description]);
}

You should switch the lines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜