potato
potato

Reputation: 4589

correct way of deleting items in collection view

I have a collection view of 20 items stored in pictures array. I am deleting selected items with this code:

            self.collectionView.performBatchUpdates({
            let selectedItems = self.collectionView.indexPathsForSelectedItems()!
            self.picturesObject.deleteItemsAtIndexPaths(selectedItems)
            self.collectionView.deleteItemsAtIndexPaths(selectedItems)

            }, completion: {_ in})

this is the implementation of picturesObject's deleteItemsAtIndexPaths:

func deleteItemsAtIndexPaths(indexPaths:[NSIndexPath]){
        for indexPath in indexPaths{
            pictures.removeAtIndex(indexPath.item)
        }
    }

The problem I'm facing is the following. Every time a selected item in collection view is deleted, the pictures array gets smaller. If I delete the first item, than pictures array is only 19 items big. If I than try to delete item number 20 in collection view, the array index gets out of bounds because pictures array is now only 19 object big, but I wanted to delete the 20iest object stored in indexpath.item.

What is the correct way of deleting items in collection view?

EDIT:/// collection view methods

  func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        collectionView.allowsMultipleSelection = true

        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picturesObject.pictures.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ShopCell
        cell.imageView.image = picturesObject.pictures[indexPath.item]

        return cell
    }

Upvotes: 1

Views: 2613

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

Before looping through your array in deleteItemsAtIndexPaths, sort your indexPaths in descending order. Then, if you delete item number 19, the next to delete is guaranteed to be less than 19.

Upvotes: 4

Related Questions