目前我有一个UICollectionViewCell,当按下一个按钮(右上角的X)时,它应该从coreData中删除,然后重新加载UICollectionView:
截至目前,当我按下" X"按钮没有任何反应,虽然我注意到在我停止模拟器并将其重新打开之后,coreData中保存的所有项目都消失了。应该发生的事情只是在" X"之后的特定细胞。按下需要立即消失并从coreData中删除。这是代码:
// MARK: CoreData
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
func deleteFromCoreData() -> Void {
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Movie")
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [Movie]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
@IBAction func deleteButtonPressed(_ sender: Any) {
self.deleteFromCoreData()
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}