2014-03-19 34 views
0

UICollectionViewController这是删除代码。UICollectionView项目删除引发异常

- (IBAction)tapRead:(id)sender 
{ 
    if (self.editing) 
    { 
     BookCell *cell = (BookCell*)[[sender superview] superview]; 
     NSArray *arr = [NSArray arrayWithObjects:cell.ipath, nil]; 

     _totalCount--; 
     NSLog(@"total: %d", _totalCount); 

     [self.collectionView deleteItemsAtIndexPaths:arr]; 
    } 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return _totalCount; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; { 
    BookCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"BookCell" forIndexPath:indexPath]; 
    cell.ipath = indexPath; 

    if (self.editing) { 
     [cell engageEditMode]; 
    } 
    else 
    { 
     [cell exitEditMode]; 
    } 

    return cell; 
} 

现在当我总是从最后删除项目,它工作得很好。然而,当我删除一些从一开始,有的从中间,在某些时候我有一个例外,当我尝试删除最后一个元素:

'NSInternalInconsistencyException', reason: 'attempt to delete item 24 from section 0 which only contains 20 items before the update' 

我不知道如何调试这...

+0

我的猜测是,你没有删除从array.Please对象从阵列中删除该对象并重新加载集合视图 – vin

+0

@vin看到我的回答,摆出相同。 –

回答

0

我认为这个问题和从UITableView中删除一个项目而不更新数据源,从而导致异常时出现的问题是一样的。请尝试以下操作:

[self.datasource removeObjectAtIndex:iPath.row]; 
//... delete the row from the collectionView. 
+0

现在我没有自己的数据源。只需使用_totalCount来模拟它。 – Pablo

+0

@Pablo,我明白了。你有没有试过NSLogging的indexPath,以确保它是正确的,并引用你想删除的行的indexPath? –

+0

问题可能在这里:'cell.ipath = indexPath'。我认为这是完全错误的方式来设置每个单元格的索引路径,并且在删除期间它将覆盖正确的索引路径。必须有更好的方式知道哪个单元格按钮按下指向... – Pablo