我正在用 Swift 编写一个时间跟踪应用程序,但在删除某项事件所花费的时间时遇到问题。我的删除函数将其从 2 个 View 的 tableView 中隐藏,并且似乎将其从核心数据中删除,但该时间并没有从我的“今天花费的总小时数”函数中删除。
从历史记录中删除的代码。这适用于两个不同 View Controller 中的 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
}
}
获取今天事件数组的代码:
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
}
如果我关闭模拟器并再次运行,总时间会按预期减少,因此在关闭模拟器之前不得触发删除。请帮忙,我已经被困在这个问题上有一段时间了。
最佳答案
正如 @vadian 所指出的,您的核心问题是 main
完全独立于您在屏幕上放置的任何内容。您创建一个 View Controller ,修改它,然后扔掉它。
您的MainViewController
应该观察核心数据并在数据更改时修改自身。这将导致它按照您的预期进行更新。
关于ios - 删除 Core Data 对象但它仍然显示在 NSFetchedResultsController 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776769/