skip to Main Content

So I’m trying to implement a swipe delete of my favorite items off the favorites tab. The swipe implementation works but when I go back to the Favorites Tab, the item deleted reappears. I’m using core data and I know it is not deleting it from core data but not sure how to fix it. This is my file for the favorites tab:

import UIKit
import CoreData

class FavAnimeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var tableView: UITableView!
    
    var favorites = [NSManagedObject]()
    var numAnime = 0
    var managedObjectContext: NSManagedObjectContext!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = self
        tableView.delegate = self
        // Do any additional setup after loading the view.
    }
    //loads every time view appears
    override func viewDidAppear(_ animated: Bool) {
        load()
    }
    
    func load() {
        //1
        guard let appDelegate =
                UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        let managedContext =
            appDelegate.persistentContainer.viewContext
        //2
        let fetchRequest =
            NSFetchRequest<NSManagedObject>(entityName: "Favorite")
        //3
        do {
            favorites = try managedContext.fetch(fetchRequest)
            tableView.reloadData()
        } catch let error as NSError {
            print("Could not fetch. (error), (error.userInfo)")
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return favorites.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier:  "FavTableViewCell") as! FavTableViewCell
        
        let favAnime = favorites[indexPath.row]
        cell.favtitleLabel.text = favAnime.value(forKeyPath: "title") as? String
        cell.favsumLabel.text = favAnime.value(forKeyPath: "synopsis") as? String
        if let poster = favAnime.value(forKey: "poster") as? String{
            let posterUrl = URL(string: poster)!
            cell.favposterView.af.setImage(withURL: posterUrl)

        }
        
        return cell
    }
    //MARK: Delete favorite items
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            favorites.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
        }
    }
    
}

if any can help that be great

2

Answers


  1. The changes (in this case Delete) wont be seen affected until you save the state of the NSManagedObjectContext, Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or location in the object graph. Once an object has been deleted from the context, we can then call saveContext() to write that change back to the persistent store so that the change is permanent.

    do {
      try managedObjectContext.save()
    } catch (let error) {
      print(error.localizedDescription)
    }
    

    Remember: you must call saveContext() whenever you want your changes to persist.

    I Hope I Helped!

    Core Data | nsmanagedobjectcontext

    Login or Signup to reply.
  2. Delete from CoreData

       func deleteParticularRecord(id:String){
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
               // use predicate for delete particular record from coredata.
            let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "EnitityName")
            let predicate = NSPredicate(format: "id = '(id)'")
                fetchRequest.predicate = predicate
            let objects = try! context.fetch(fetchRequest)
                for obj in objects {
                    context.delete(obj as! NSManagedObject)
                }
                do {
                    try context.save() // <- remember to put this :)
                } catch {
                    // Do something... fatalerror
                }
            }
        // Call 
         func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
            if editingStyle == .delete {
                favorites.remove(at: indexPath.row)
                tableView.deleteRows(at: [indexPath], with: .fade)
                // use id or object id
                deleteParticularRecord(id: "_Id_")
            } else if editingStyle == .insert {
                // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
            }
        }
    

    // Hope its works 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search