Sarah Malik Sarah Malik - 2 years ago 120
iOS Question

Swift 3: How to delete the single record in the Core Data when a UIbutton is Pressed

I have a function, where I can add the Profile to the favourite list (which saves through Core Data) and when I want to mark it as Not Favourite, it should delete from the Core data and also from the TableList View (Favourite View Controller).

The code what I have so far, deletes all the records from the list instead deleting the specific record.

Please Find the code Below:-

@IBAction func saveFav(_ sender: UIButton) {

let propertyToCheck = sender.currentTitle!
var proID = saved_id
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = FavProfile(context: context)

switch propertyToCheck {
case "Add to Favourite":
// Link Task & Context
task.busName = bussinessName
task.profileID = Int32(id!)!
print ("saved id is: - \(task.profileID)")
print ("saved profile name is: - \(task.busName)")
fav_remove_fav_button_label.setTitle("Remove From Favourite", for: .normal)

// Save the data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()

let _ = navigationController?.popViewController(animated: true)

let alert = UIAlertController(title: "Alert", message: "Added to your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

case "Remove from Favourite":



let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
let moc = getContext()
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [FavProfile]

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 {

}




let alert = UIAlertController(title: "Alert", message: "Removed from your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
// self.favtable.tableView.reloadData()


default: break
}
}


I dont know what I need to fix here that only deletes the specific record.

Thanks for the time and effort.

Ada Ada
Answer Source
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
    let predicate = NSPredicate(format: "profileID == %@", id as CVarArg)
    fetchRequest.predicate = predicate
    let moc = getContext()
    let result = try? moc.fetch(fetchRequest)
    let resultData = result as! [FavProfile]

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

use predicate for profileID.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download