删除行后,从核心数据中保存和获取集合视图单元格

时间:2016-12-31 16:24:28

标签: ios swift core-data

我添加了一个滑动手势,允许我通过向左滑动删除我的集合视图中的单元格。这一点没有问题。我的问题是在删除和使用新数据获取我的集合视图后更新核心数据。这是我的代码:

    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()
        }

1 个答案:

答案 0 :(得分:1)

您无法从托管对象上下文中删除索引路径。您必须先检索托管对象才能将其删除:

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