Volkan
Volkan

Reputation: 359

Saving and fetching collection view cell from core data after deleting a row

I have added a swipe gesture which allow me to delete a cell in my collection view by swiping left. There is no problem at this point. My problem is updating core data after deleting and fetching my collection view with new data. Here is my code:

    var myJokes : [MyJokes] = []

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
        {
            let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell2
            let task = myJokes[indexPath.row]
            cell.textLabel.text = task.favoriteJokes!

            let cSelector = #selector(reset(sender:))
            let leftSwipe = UISwipeGestureRecognizer(target: self, action: cSelector )
            leftSwipe.direction = UISwipeGestureRecognizerDirection.left
            cell.addGestureRecognizer(leftSwipe)
            return cell
        }

    func reset(sender: UISwipeGestureRecognizer) {
            let cell = sender.view as! CollectionViewCell2
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            let i = self.myCollectionView.indexPath(for: cell)?.item

            // When i use this line i get an error: 'Cannot convert value of type 'Int' to expected argument type 'NSManagedObject'*
            context.delete(i)
            // When i use this one, i am able to delete the cell but core data does not update
            myJokes.remove(at: i!)

            (UIApplication.shared.delegate as! AppDelegate).saveContext()
            do
            {
                myJokes = try context.fetch(MyJokes.fetchRequest())
            } catch {}

            self.myCollectionView.reloadData()
        }

Upvotes: 0

Views: 798

Answers (1)

nils
nils

Reputation: 1976

You cannot delete an index path from a managed object context. You have to retrieve the managed object first in order to delete it:

guard let i = i else { /* handle this case */ }
let deletable = myJokes[i]
myJokes.remove(at: i)
context.delete(deletable)

Upvotes: 1

Related Questions