【问题标题】:Deleting Core Data object but it still shows up in NSFetchedResultsController?删除核心数据对象但它仍然显示在 NSFetchedResultsController 中?
【发布时间】: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
}

如果我关闭模拟器并再次运行,总时间会按预期减去,所以在我关闭它之前不能触发删除。请帮忙,我已经被困了一段时间了。

【问题讨论】:

  • 您可以保存上下文以提交删除,mainMainViewController 的全新实例,而不是故事板中预期的实例。

标签: ios swift uitableview core-data nsfetchedresultscontroller


【解决方案1】:

正如@vadian 所说,您的核心问题是main 完全独立于您在屏幕上放置的任何内容。您创建一个视图控制器,对其进行修改,然后将其丢弃。

您的MainViewController 应该观察核心数据并在数据更改时自行修改。这将导致它按照您的预期进行更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2012-06-17
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多