When i'm delete cell from my CollectionView app is crashed (CoreData).
I'm use custom button in CollectionView.
var cardItems = [NSManagedObject]()
cell.MenuButton.layer.setValue(indexPath.row, forKey: "index")
cell.MenuButton.addTarget(self, action: #selector(MenuCell), for: UIControl.Event.touchUpInside)
Error
EDIT (It's work)
let i: Int = (sender.layer.value(forKey: "index")) as! Int
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let indexPath = IndexPath(item: i, section: 0)
let itemToDelete = self.cardItems[indexPath.item]
self.cardItems.remove(at: indexPath.item)
managedContext.delete(itemToDelete)
appDelegate.saveContext()
self.collectionView.reloadData()
First of all, it's not a good way to identify the click button. Instead, you can set button tag as indexPath.row like below:
menuButton.tag = indexPath.row
cell.MenuButton.layer.setValue(indexPath.row, forKey: "index")
Also improve your coding skills see below:
cell.MenuButton.addTarget(self, action: #selector(onClickMenuButton(_:)), for: .touchUpInside)
Implement this selector as:
let i: Int = (sender.layer.value(forKey: "index")) as! Int
func onClickMenuButton(_ sender: UIButton) {
let task = self.cardItems[sender.tag]
if let managedContext = task.managedObjectContext {
managedContext.delete(task)
do {
try managedContext.save()
self.cardItems.remove(at: sender.tag)
let indexPath = IndexPath(row: i, section: 0)
self.collectionView.deleteItems(at: [indexPath])
} catch {
print("Failed to delete")
}
}
}