Abdulhafeez Shagaya Abdulhafeez Shagaya - 3 months ago 10
iOS Question

Reload tableview after deleting from core data

I'm deleting all the items in

CoreData
when a button is clicked but the app will crash after deleting and give this error


fatal error: unexpectedly found nil while unwrapping an Optional value


Code i have try:

if let rf = response{
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: moc)
fetchRequest.includesPropertyValues = false
let context:NSManagedObjectContext = appDel.managedObjectContext
let moc = context
do {
if let results = try moc.executeFetchRequest(fetchRequest) as? [NSManagedObject] {
for result in results {
moc.deleteObject(result)
self.tableView.reloadData()
}
try moc.save()

}
} catch {
print("FAILED")
}

Answer

You need to reinitialize your array or remove all the object from array, also then reload the table after for loop like this.

for result in results {
    moc.deleteObject(result)        
}
try moc.save()
yourArray = [NSManagedObject]() //The array that you have used with UITableViewDataSource method
//OR
yourArray.removeAll()
self.tableView.reloadData()