gpt4 book ai didi

ios - 删除行后从核心数据中保存和获取 Collection View 单元格

转载 作者:行者123 更新时间:2023-11-28 15:58:32 25 4
gpt4 key购买 nike

我添加了一个滑动手势,允许我通过向左滑动来删除我的收藏 View 中的一个单元格。此时没有问题。我的问题是在删除并使用新数据获取我的 Collection View 后更新核心数据。这是我的代码:

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

最佳答案

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

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

关于ios - 删除行后从核心数据中保存和获取 Collection View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41410022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com