Ios 在UICollectionView中的当前索引之前添加对象

Ios 在UICollectionView中的当前索引之前添加对象,ios,objective-c,uicollectionview,Ios,Objective C,Uicollectionview,我有一个简单的集合视图,它有两种类型的单元格。计数器单元格和“添加”单元格。我的目标是在添加新对象后,让“add”单元格保留在索引的末尾。当我运行应用程序时,我的“添加”单元格会出现,但当按下“添加”按钮时会出现错误 以下是错误: 由于未捕获异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效更新:无效 第0节中的项目数。表中包含的项目数 更新(1)后的现有节数必须等于 更新(1)之前该节中包含的项目,加或减 从该节插入或删除的项目数(插入1,

我有一个简单的集合视图,它有两种类型的单元格。计数器单元格和“添加”单元格。我的目标是在添加新对象后,让“add”单元格保留在索引的末尾。当我运行应用程序时,我的“添加”单元格会出现,但当按下“添加”按钮时会出现错误

以下是错误:

由于未捕获异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效更新:无效 第0节中的项目数。表中包含的项目数 更新(1)后的现有节数必须等于 更新(1)之前该节中包含的项目,加或减 从该节插入或删除的项目数(插入1, 0)并加上或减去移入或移出的项目数 该部分(0移入,0移出)。'

这是我的代码:

// retrievedCounters is an NSMutableDictionary

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
   // only want one section
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    // get the current count and add one for the "add" cell
    return retrievedCounters.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell;

    // check whether the index path is at the very end and add the appropriate cell

    if (indexPath.row == retrievedCounters.count) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddCounter" forIndexPath:indexPath];
    }

    else {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CounterCell" forIndexPath:indexPath];
    }

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];

     // insert new counter at index path
     [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:retrievedCounters.count-1 inSection:0]]];

}

谢谢所有能帮忙的人

该错误表示更改数据源时出现数据源问题。可变字典中的键数不正确

大概您正在使用
nsindepath
s作为键,使用所需的数据作为值。我认为使用数组更容易(
indexPath.row
将以正确的顺序指向正确的对象)

检查更改数据源中数据的更新方法。您应该确保您的词典包含预期数量的条目


在错误消息中,插入前后的1项似乎表示您的字典可能变为
nil
,因此返回零计数。确保在添加新对象时,在对象数组中有一个正确实例化的实例变量。

为新对象创建新数组,然后像这样添加它

 [existingArray addObjectsFromArray:newarray];

序列将被维护

他使用的不是对象数组,而是字典。你是对的,我的数据源没有被正确更改。有时能有一双新的眼睛来看看你的代码是很好的。非常感谢。