Reputation: 69
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. This works for tableView in two different view controllers:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let historyToDelete = fetchController.objectAtIndexPath(indexPath)
let todaysActivitiesArray = CoreDataHandler.sharedInstance.fetchCoreDataForTodayActivities()
let main = MainViewController()
var totalDuration = main.calculateTotalDurationForToday()
let historyDel = fetchController.objectAtIndexPath(indexPath) as! History
totalDuration = totalDuration - Int(historyDel.duration!)
CoreDataHandler.sharedInstance.deleteObject(historyToDelete as! NSManagedObject)
main.totalduration = totalDuration
}
}
Code for getting today Activity array:
func fetchCoreDataForTodayActivities() -> [History] {
let fetchRequest = NSFetchRequest()
let entityDescription = NSEntityDescription.entityForName("History", inManagedObjectContext: self.backgroundManagedObjectContext)
fetchRequest.entity = entityDescription
let dateDescriptor = NSSortDescriptor(key: "startDate", ascending: false)
fetchRequest.sortDescriptors = [dateDescriptor]
let startDate = NSDate.dateByMovingToBeginningOfDay()
let endDate = NSDate.dateByMovingToEndOfDay()
let predicate = NSPredicate(format: "(startDate >= %@) AND (startDate <= %@)", startDate, endDate)
fetchRequest.predicate = predicate
return (fetchCoreDataWithFetchRequest(fetchRequest) as! [History])
}
Code for calculating today's activity:
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 subtracts as expected, so the deletion must not be triggered until I close it. Please help, I've been stuck on this a while now.
Upvotes: 0
Views: 105
Reputation: 299265
As @vadian notes, your core problem is that main
is completely independent of anything you put on the screen. You create a view controller, modify it, and then throw it away.
Your MainViewController
should observe Core Data and modify itself when the data changes. That will cause it to update as you expect.
Upvotes: 0