【发布时间】:2016-06-12 16:49:30
【问题描述】:
我正在用 Swift 编写一个时间跟踪应用程序,但在删除某项活动所花费的时间时遇到了问题。我的删除功能在 2 个视图上将其从 tableView 中隐藏,并似乎将其从 Core Data 中删除,但时间并未从我的“今天花费的总小时数”功能中删除。
从历史中删除的代码。这适用于两个不同视图控制器中的 tableView:
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
}
}
获取今日Activity数组的代码:
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])
}
计算今天活动的代码:
func calculateTotalDurationForToday() -> NSInteger {
var sumOfDuration = 0
for history in todaysActivitiesArray {
sumOfDuration += (history.duration?.integerValue)!
}
return sumOfDuration
}
如果我关闭模拟器并再次运行,总时间会按预期减去,所以在我关闭它之前不能触发删除。请帮忙,我已经被困了一段时间了。
【问题讨论】:
-
您可以保存上下文以提交删除,
main是MainViewController的全新实例,而不是故事板中预期的实例。
标签: ios swift uitableview core-data nsfetchedresultscontroller