how to delete a particular row data in coredata database in swift

how to delete a particular row data in coredata database in swift




PLease help me out

Here is my code
//

import UIKit
import CoreData


class SavedPageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate , NSFetchedResultsControllerDelegate  {


    @IBOutlet weak var tableView: UITableView!

    var tableTitleArray = [String]()
    var tableDetailArray = [String]()
    var tableTypeArray = [String]()
    var tableHoursArray = [String]()
    var tableImageArray = [NSData]()


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(animated: Bool) {
// core data - show
         let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
         let context:NSManagedObjectContext = appDel.managedObjectContext

        var request = NSFetchRequest(entityName: "SavedIdea")
        request.returnsObjectsAsFaults = false;

        do {
            var result:NSArray = try context.executeFetchRequest(request)

            if (result.count > 0) {
                 self.tableTitleArray = result.valueForKey("heading") as! [String]
                 self.tableDetailArray = result.valueForKey("detail") as! [String]
                 self.tableTypeArray = result.valueForKey("type") as! [String]
                 self.tableHoursArray = result.valueForKey("time") as! [String]
                self.tableImageArray = result.valueForKey("image") as! [NSData]
            }else{
                print("0 result appear....error")}
            tableView.reloadData()
        }catch {
            let fetchError = ("returned error is \(error as! NSError)")
            print(fetchError)
        }
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.tableTitleArray.count
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as! OTPTableViewCell

        cell.LabelTitle.text = tableTitleArray[indexPath.row]
        cell.LabelDetail.text = tableDetailArray[indexPath.row]
        cell.LabelType.text = tableTypeArray[indexPath.row]
        cell.LabelHours.text = String(tableHoursArray[indexPath.row])+"h"
        if tableImageArray[indexPath.row].length > 0  {          
            cell.ImgView.image =  UIImage(data: tableImageArray[indexPath.row])
        }else{
            cell.imageWidthConstraints.constant = 0
        }

        return cell
    }


    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == .Delete {

        let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        let context:NSManagedObjectContext = appDel.managedObjectContext


   /*     let deleterequest = NSFetchRequest(entityName: "SavedIdea")
        deleterequest.returnsObjectsAsFaults = false

        do {
            let savedData = try context.executeFetchRequest(deleterequest)

            if savedData.count > 0 {

                for result: AnyObject in savedData{
                    context.deleteObject(result.valueForKey("heading"))
                    print("NSManagedObject has been Deleted")
                }
                try context.save() } } catch {}



     }
    }

i want to delete a complete row from tableview i.e heading,detail,type etc . My entity name is SavedData. I tried few tutorial but they didnt satisfy my needs . when we slide right then delete appear but dont working as i dont know the code.



1) This way you can delete Data from coredata based on Entity : Here is simple function to delte user entity data from coredata : Hope it helps //Delete info from Core data

func deleteUserInfo()  {    
    let context = appdelegate.managedObjectContext
    let coord   = appdelegate.persistentStoreCoordinator

    let fetchRequest = NSFetchRequest(entityName: "entityname")
    //Here is the field on which u need to chk which record u want to delete just pass here in value ( acutal value) unique key = field in coredata 
    let predicate = NSPredicate(format: "uniqueKey == %@", "value")
    fetchRequest.predicate = predicate
    if #available(iOS 9.0, *) {
       //You can put condition to delete data accordingly
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

        do {
            try coord.executeRequest(deleteRequest, withContext: context)
        }

        catch let error as NSError {
            //Error handling
        }

        catch {}

    } else {

        // Fallback on earlier versions
        do {

           let users: NSArray = try appdelegate.managedObjectContext.executeFetchRequest(fetchRequest)

        //You can put condition to delete data accordingly
        for user in users {
            appdelegate.managedObjectContext.delete(user)
        }

        try appdelegate.managedObjectContext.save()

        } catch let error as NSError {
            //Error handling
        }

        catch {}
    }
}




2) I hope this will be useful for deleting the particular row using the index position in core data

func tableView(_ tableView: UITableView, commit editingStyle: 

UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) 

{
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let context = appDelegate.persistentContainer.viewContext

    let requestDel = NSFetchRequest<NSFetchRequestResult>(entityName: "Contacts")
    requestDel.returnsObjectsAsFaults = false

    do {

        let arrUsrObj = try context.fetch(requestDel)

        let objectUpdate = arrUsrObj as! [NSManagedObject]

            context.delete(objectUpdate[indexPath.row]) // Deleting Object

    } catch {
        print("Failed")
    }

    // Saving the Delete operation
    do {
        try context.save()
        print("deleted")
        fetch()


    } catch {
        print("Failed saving")
    }


}


Put your proposition in a comment !

swift core-data


No comments

Powered by Blogger.