xxmilcutexx
xxmilcutexx

Reputation: 67

unable to use tableView.deleteRowsAtIndexPaths with coreData

I have created a list of employees and display it tableView. User should be able to delete an employee when select a delete action. I tested it on an array, it's working however when I changed it to core data, it crashed. Without

self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

The app seemed to work but the deleted row still exist with empty labels.(Without the name and title)

FavEmployeeViewController.swift

//MARK:- Table Functions
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    if searchController.active && searchController.searchBar.text != "" {
        return filteredEmployees.count
    }
    //coredata
    return employeeStore.testCoreData.count
}

//MARK:- TEST coredata
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Create an instance of UITableViewCell, with default appearance
    let cell = tableView.dequeueReusableCellWithIdentifier("EmployeeCell", forIndexPath: indexPath) as! EmployeeCell
    cell.updateLabels()

    let item = employeeStore.testCoreData[indexPath.row]

    cell.nameLabel.text = item.valueForKey("name") as? String
    cell.jobPosition.text = item.valueForKey("title") as? String

    return cell

}


//MARK:- Edit bar Button
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    // If the table view is asking to commit a delete command...
    if editingStyle == .Delete {
        let item = employeeStore.testCoreData[indexPath.row]
        let title = "Delete \(item.valueForKey("name") as! String)?"
        let message = "Are you sure you want to delete this item?"

        let ac = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet)
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
        ac.addAction(cancelAction)

        let deleteAction = UIAlertAction(title: "Delete", style: .Destructive,
                                         handler: { (action) -> Void in
                                            // Remove the item from the store
                                            debugPrint("index", indexPath.row)
                                            self.employeeStore.testremoveEmployee(indexPath.row)
                                            // Also remove that row from the table view with an animation
                                            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
                                                                                            debugPrint("index", indexPath.row)
        })
        ac.addAction(deleteAction)

        // Present the alert controller
        presentViewController(ac, animated: true, completion: nil)
    }
}

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
    // Update the model
    employeeStore.moveEmployeeAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row)
}

EmployeeStore.swift

import UIKit
import CoreData

class EmployeeStore {
    //MARK:-Coredata
    var testCoreData = [NSManagedObject]() //storing favs entities

...

//MARK:- Test delete coreData -> removeFavEmployee
func testremoveEmployee(index: Int) {
    debugPrint("testremoveEmployee")
    //retrieve from CoreData
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let employee = testCoreData[index]

    let _: NSError! = nil
    do {
        managedContext.deleteObject(employee)
        debugPrint("manage2delete")
        try managedContext.save()

    } catch {
        print("error : \(error)")
    }
}

Upvotes: 1

Views: 108

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You need to also delete object from self.employeeStore array you have just deleted it from CoreData so add self.employeeStore.remove(at: indexPath.row) after you delete object from CoreData.

self.employeeStore.testremoveEmployee(indexPath.row)

// Also remove that object from Array
self.employeeStore. testcoreData.removeAtIndex(indexPath.row)

// Now remove that row from the table view with an animation
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

Upvotes: 1

Related Questions