Search code examples
objective-ccore-dataxcode4

Can we change Query in NSFetchedRequestController?


Some says we cannot change the request object. Some says we can change the query. Some says we cannot change the predicate.

How do you change the query if you do not change the predicate?

That's kind of strange right.


Solution

  • It's not an SQL query, it's fetch. A query is a SQL specific concept while a fetch is a Core Data concept that works with any type of Core Data store.

    You can change the fetchRequest value of a NSFetchedResultsController but its somewhat involved. From the docs:

    Modifying the Fetch Request

    You cannot simply change the fetch request to modify the results. If you want to change the fetch request, you must:

    (1) If you are using a cache, delete it (using deleteCacheWithName:).

    Typically you should not use a cache if you are changing the fetch request.

    (2) Change the fetch request.

    (3) Invoke performFetch:.

    It is the cache that causes the problems with modifying the fetch request.

    You can also change the predicate of a NSFetchRequest object but if you use that fetch with a fetched results controller, you have to perform the above steps.

    The problems comes when the cached objects are not the same set returned by the new fetch request. Often it is simpler and cleaner to just create a new fetch request object or a new fetched results controller object.

    You do have to freeze the tableview with beginUpdate while all this is going on otherwise the tableview's rows and sections will come out of sync with the data causing a crash.