ios - 删除 Core Data 对象但它仍然显示在 NSFetchedResultsController 中?

标签 ios swift uitableview core-data nsfetchedresultscontroller

我正在用 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/

相关文章:

objective-c - Objective-C : How to add "plus" button in cell

ios - 自动布局 UILabel 高度在第二个 View 外观上发生变化

ios - 无法解析 RealmSwift 中的格式字符串

ios - GameScene 尺寸比我的设备屏幕尺寸宽

ios - 如何解决 tableView 上下文中的 "Reactive<_>' is ambigitude"错误

swift - 保持节点的 X 轴和 Z 轴与地面平行,同时旋转 Y 轴以面向相机

ios - 检查创建的指针对象是否小于今天 Parse.com

iOS 复合谓词

ios - touchesBegan 与 UITapGestureRecognizer

ios - 在 TableView 单元格 iOS 中设置 UILabels 的值