1

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.

Parsania Hardik
  • 4,593
  • 1
  • 33
  • 33
Hitesh Mor
  • 72
  • 1
  • 11
  • you are deleting entity itself instead of particular row, Fetch that particular row and perform delete action and reload tableview – Jan Aug 29 '16 at 11:30
  • Check this http://stackoverflow.com/questions/26047013/delete-data-from-coredata-swift – Nitesh Aug 29 '16 at 12:12
  • Mark it correct answer if it solve your problem – Shobhakar Tiwari Aug 29 '16 at 12:18
  • With your weird code it is very complicated (and inefficient) to do that. First you have to search and fetch the `NSManagedObject` because you threw away the reference, then you have to remove the item at row index in **all** arrays representing the data source, then you have to delete the `NSManagedObject` in Core Data and finally call `deleteRowsAtIndexPaths` in the tableView. – vadian Aug 30 '16 at 07:46

2 Answers2

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 {}
    }
}
Shobhakar Tiwari
  • 7,862
  • 4
  • 36
  • 71
  • i want to delete the selected Row from table view so i put this code in - func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { }.......................it is showing me error on this line when i put indexpath.row on user like this ..appDel.managedObjectContext.delete(user(indexPath.row)) – Hitesh Mor Aug 29 '16 at 12:31
  • chck parameter u passing integer ? – Shobhakar Tiwari Aug 29 '16 at 18:06
  • i am Showing my data in viewcontroller using this code - – Hitesh Mor Aug 30 '16 at 07:16
  • chck updated answer , changed code accordingly , in coredata u need to use Predicate to fetch result and then u can delete just pass value and field according to your requirement – Shobhakar Tiwari Aug 30 '16 at 07:24
1

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


}