【问题标题】:Delete record in Core Data with CollectionView使用 CollectionView 删除 Core Data 中的记录
【发布时间】:2019-03-05 23:27:06
【问题描述】:

当您点击 CollectionView 单元格中的关闭按钮时,我想删除核心数据中的一条记录。我在 Collection View Cell 控制器中创建了一个 UIButton,并在 CollectionView Controller 文件中添加了扩展名。

indexPath 给出了一个数字,我创建了 let deleteCellNumber,但我收到了错误:

'无法将'IndexPath.Element(又名'Int')类型的值转换为预期的参数类型'NSManagementObject'

extension soundboardVC: SoundboardCellDelegate {
    func delete(cell: soundboardCellVC) {

        if let indexPath = collectionView?.indexPath(for: cell) {

            let soundRequest:NSFetchRequest<Soundboard> = Soundboard.fetchRequest()
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            let deleteCellNumber = indexPath[1]

            context.delete(deleteCellNumber)

            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do {
                soundBoardData = try managedObjectContext.fetch(soundRequest)
            } catch {
                print("Fetching Failed")
            }
        }
    }
}

【问题讨论】:

  • 与错误无关,但使用indexPath.item而不是indexPath[1]

标签: ios swift core-data uicollectionview


【解决方案1】:

错误很明显:

context.delete(... 需要一个 NSManagedObject 实例,但您传递了一个整数(顺便说一下,indexPath[1] 是获取 item / row 值的一种非常诡异但有效的方法)。

假设您有一个数据源数组soundBoardData,在集合或表视图中删除 Core Data 对象的常用方法是

extension soundboardVC: SoundboardCellDelegate {
    func delete(cell: soundboardCellVC) {

        if let indexPath = collectionView?.indexPath(for: cell) {

            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let context = appDelegate.persistentContainer.viewContext
            let itemToDelete = soundBoardData[indexPath.item]
            soundBoardData.remove(at: indexPath.item)
            context.delete(itemToDelete)
            collectionView!.deleteItems(at: indexPath)
            appDelegate.saveContext()
        }
    }
}

不要重新获取数据,删除数据源数组中的项目,然后删除托管对象上下文中的项目,从集合视图中删除行(带动画)并保存上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2018-07-02
    • 2014-05-06
    • 2017-06-20
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多