NSFetchedResultsController order not changed when it should

I have a NSFetchedResultsController (or NSFRC) that is really pretty standard;

  • No predicate set
  • Fetch all items of one entity kind
  • Sorted by a NSDate field (descending)
  • Delegate is set
  • Data is fetched
  • Up next the data gets updated:

  • A background thread updates the data
  • the field used in the sort order gets changed among with other fields.
  • The changes are merged into the main threads' ObjectContext
  • The NSFRC nicely passes on the changes to the TableView, except for the order changes .
  • Is doesn't matter if I animate changes, or simply do reloadData() , data is changed, the order isn't.
  • I would expect the delegate for example to swap the first and second row because the second row's date value is now higher than the first one.

    If I re-open the ViewController (so the fetch is done again on a new VC and NSFRC ) the order does change as expected. But thats anything but intuitive for the user.

    Could anyone please point me into possible places to search for my mistake?

    Just to reiterate:

  • Changes to content are being delegated, ie another field contains text, which does get changed.
  • The order is not being changed. So it appears the SortOrder is only used when fetching the very first time.

  • Here's two screenshots, the second line (date) is also the sort order. The second image shows updated data but a wrong sort order.

    Before

    数据更新之前的情况

    After

    数据更新后的情况


    When your data changes you may need to nil the NSFRC and let it do its thing. For example. Lets say that you have a function which changes the order of your items. If you are using standard Apple code, you should have something like this

    func updateSort () {
    
        _fetchedResultsController = nil //Here is the magic
        tableView.reloadData()
    }
    
    // MARK: - Core Data
    var fetchedResultsController:NSFetchedResultsController {
        if _fetchedResultsController != nil {
            return _fetchedResultsController!
        }
    
        // do your basic initialization and set the delegate and return it
    
        return _fetchedResultsController!
    
    }
    
     var _fetchedResultsController: NSFetchedResultsController? = nil
    
    链接地址: http://www.djcxy.com/p/36160.html

    上一篇: 使用NSFetchedResultsController和SortDescriptors对部分内的项目进行排序

    下一篇: NSFetchedResultsController的顺序应该不会改变