Sammy
Sammy

Reputation: 69

iOS: Deleting object from Core Data deletes it in table view but not in other parts of app

I am writing a time tracking app in Swift, and I have a problem with deleting a time spent on an activity. My delete function hides it from tableView on 2 views and appears to remove it from Core Data, but the time doesn’t delete from my "total hours spent today" function.

Code for deleting from history:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: 
UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        let historyToDelete = fetchController.objectAtIndexPath(indexPath)
        let main = MainViewController()
        var totalDuration = main.totalduration
        let historyDel = fetchController.objectAtIndexPath(indexPath) as! History
        totalDuration = totalDuration - Int(historyDel.duration!)
        CoreDataHandler.sharedInstance.deleteObject(historyToDelete as! NSManagedObject)
    }
}

Code for deleting in CoreDataHandler:

func deleteObject(object: NSManagedObject) {
backgroundManagedObjectContext.deleteObject(object)
saveContext()
}

function for calculating total duration of day:

func calculateTotalDurationForToday() -> NSInteger {
    var sumOfDuration = 0
    for history in todaysActivitiesArray {
        sumOfDuration += (history.duration?.integerValue)!
    }
    return sumOfDuration
}

If I close the simulator and run again the total time spent today removes the object, so it must not be triggered until I close the app. Any advice on how to fix this?

Upvotes: 1

Views: 254

Answers (1)

Lou Franco
Lou Franco

Reputation: 89142

Deleting a CoreData object removes the row from the table and if you fetched again, you would not get an object representing that row.

Existing objects that represent that row don't just remove themselves from arrays they are in. You have to listen to CoreData save events (or Notification Center, or remove it directly, etc) to respond to the CoreData things that are happening. NSFetchedResultsController does that, but if todaysActivitiesArray is just an array, it would not.

Upvotes: 1

Related Questions