问题: - 从核心数据中删除行时遇到问题。每当我执行删除功能时,行中的值将更改为0,但该行仍存在于Core数据库中。如何完全删除下面编写代码中的行?
我有tableView
显示一些列表,每个单元格都有一个带灰色书签图像的按钮作为默认值。
当我点击bookmarkBtn
时,按钮图像变为蓝色图像,数据由coreData存储。再次单击后,bookmarkBtn
再次变为灰色图像,核心数据中的条目将被删除。
//Code:- **when bookmarkBtn is clicked.**
@IBAction func btnClicked(_ sender: UIButton)
{
let position: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: position)!
sender.tag = indexPath.row
let cell: TableViewCell = self.tableView.cellForRow(at: indexPath) as! TableViewCell
// print("Favorite button tapped")
if sender.isSelected != true
{
cell.bookmarkBtn.setImage(UIImage(named: "bookmark_blue"), for: UIControlState.normal);
sender.isSelected = true;
saveItem(itemToSave:sender.tag)
self.bookmarkArrState.replaceObject(at: (indexPath.row), with:1);
}
else
{
cell.bookmarkBtn.setImage(UIImage(named: "bookmark_grey" ), for: UIControlState.normal);
sender.isSelected = false;
removeData(itemToDelete: sender.tag)
self.bookmarkArrState.replaceObject(at: (indexPath.row), with:0)
}
}
//Code:- **Saving values in CoreData**
func saveItem(itemToSave: Int){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//**Note:** Here we are providing the entityName **`Entity`** that we have added in the model
let entity = NSEntityDescription.entity(forEntityName: "AddedBookmark", in: context)
let myItem = NSManagedObject(entity: entity!, insertInto: context)
myItem.setValue(itemToSave, forKey: "indexNo")
do {
try context.save()
}
catch{
print("There was an error in saving data")
}
}
//**Code:- Deleting Data when bookmarkBtn is clicked again**
func removeData(itemToDelete: Int)
{
let mngdCntxt = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//**Note:** Here we are providing the entityName **`Entity`** that we have added in the model
let entity = NSEntityDescription.entity(forEntityName: "AddedBookmark", in: mngdCntxt)
let myItem = NSManagedObject(entity: entity!, insertInto: mngdCntxt)
if let dataAppDelegatde = UIApplication.shared.delegate as? AppDelegate {
let mngdCntxt = dataAppDelegatde.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "AddedBookmark")
let predicate = NSPredicate(format: "indexNo = %i", Int(itemToDelete))
print("item selected :-\(itemToDelete)")
fetchRequest.predicate = predicate
do{
var result = try mngdCntxt.fetch(fetchRequest)
print(result.count)
print(fetchRequest)
if result.count > 0{
for object in result
{
print(object)
mngdCntxt.performAndWait {
mngdCntxt.delete(result[0] as! NSManagedObject)
mngdCntxt.refreshAllObjects()
}
}
}
do {
try mngdCntxt.save()
}
catch{
print("There was an error in saving data")
}
}
catch{
}
}
}