我正在编写一个时间跟踪应用程序,当我删除记录的第一部分时间时,它会从两个视图控制器上的tableView中删除(如预期的那样),但记录的时间为"今天的总持续时间& #34;区域不会减去删除的时间。这只发生在第一个索引,其余的按预期工作。
删除对象的代码:
func tableView(tableView: UITableView, commitEditingStyle editingStyle:
UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
var historyToSubtract =
fetchController.objectAtIndexPath(indexPath) as! History
MainViewController().calculateDeletedDurationForToday(historyToSubtract)
MainViewController中的代码,用于减去已删除的持续时间:
func calculateDeletedDurationForToday(historyToSubtract: History?) -> NSInteger {
var todaysActivitiesArray = CoreDataHandler.sharedInstance.fetchCoreDataForTodayActivities()
var totalDuration = MainViewController().calculateTotalDurationForToday()
if todaysActivitiesArray.count < 1 {
totalDuration = 0
}
else {
totalDuration = totalDuration - Int(historyToSubtract!.duration!)
}
print(todaysActivitiesArray)
print(totalDuration)
CoreDataHandler.sharedInstance.deleteObject(historyToSubtract as! NSManagedObject)
CoreDataHandler.sharedInstance.saveContext()
return totalDuration
}
获取今天核心数据的代码(todaysActivitiesArray):
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])
}
我之前收到一个错误,它试图在空数组上访问索引0,所以我相信fetchCoreDataForTodayActivities()对第一个索引做了一些奇怪的事情,但我无法弄明白。