You use a fetched results controller to efficiently manage the results returned from a Core Data fetch request to provide data for a
- iOS 3.0+
- macOS 10.12+
- tvOS 3.0+
- watchOS 2.0+
While table views can be used in several ways, fetched results controllers are primarily intended to assist you with a master list view.
UITable expects its data source to provide cells as an array of sections made up of rows. You configure a fetch results controller using a fetch request that specifies the entity, an array containing at least one sort ordering, and optionally a filter predicate. The fetched results controller efficiently analyzes the result of the fetch request and computes all the information about sections in the result set. It also computes all the information for the index based on the result set.
In addition, fetched results controllers provide the following features:
Optionally monitor changes to objects in the associated managed object context, and report changes in the results set to its delegate (see The Controller’s Delegate).
Optionally cache the results of its computation so that if the same data is subsequently re-displayed, the work does not have to be repeated (see The Cache).
A controller thus effectively has three modes of operation, determined by whether it has a delegate and whether the cache file name is set.
No tracking: the delegate is set to
The controller simply provides access to the data as it was when the fetch was executed.
Memory-only tracking: the delegate is non-
niland the file cache name is set to
The controller monitors objects in its result set and updates section and ordering information in response to relevant changes.
Full persistent tracking: the delegate and the file cache name are non-
The controller monitors objects in its result set and updates section and ordering information in response to relevant changes. The controller maintains a persistent cache of the results of its computation.
Creating the Fetched Results Controller
You typically create an instance of
NSFetched as an instance variable of a table view controller. When you initialize the fetch results controller, you provide four parameters:
A fetch request. This must contain at least one sort descriptor to order the results.
A managed object context. The controller uses this context to execute the fetch request.
Optionally, a key path on result objects that returns the section name. The controller uses the key path to split the results into sections (passing
nilindicates that the controller should generate a single section).
Optionally, the name of the cache file the controller should use (passing
nilprevents caching). Using a cache can avoid the overhead of computing the section and index information.
After creating an instance, you invoke
perform to actually execute the fetch.
The Controller’s Delegate
If you set a delegate for a fetched results controller, the controller registers to receive change notifications from its managed object context. Any change in the context that affects the result set or section information is processed and the results are updated accordingly. The controller notifies the delegate when result objects change location or when sections are modified (see
NSFetched). You typically use these methods to update the display of the table view.
Where possible, a controller uses a cache to avoid the need to repeat work performed in setting up any sections and ordering the contents. The cache is maintained across launches of your application.
When you initialize an instance of
NSFetched, you typically specify a cache name. (If you do not specify a cache name, the controller does not cache data.) When you create a controller, it looks for an existing cache with the given name:
If the controller can’t find an appropriate cache, it calculates the required sections and the order of objects within sections. It then writes this information to disk.
If it finds a cache with the same name, the controller tests the cache to determine whether its contents are still valid. The controller compares the current entity name, entity version hash, sort descriptors, and section key-path with those stored in the cache, as well as the modification date of the cached information file and the persistent store file.
If the cache is consistent with the current information, the controller reuses the previously-computed information.
If the cache is not consistent with the current information, then the required information is recomputed, and the cache updated.
Any time the section and ordering information change, the cache is updated.
If you have multiple fetched results controllers with different configurations (different sort descriptors and so on), you must give each a different cache name.
You can purge a cache using
Implementing the Table View Datasource Methods
You ask the object to provide relevant information in your implementation of the table view data source methods:
Responding to Changes
NSFetched is designed to respond to changes at the model layer, by informing its delegate when result objects change location or when sections are modified.
If you allow a user to reorder table rows, then your implementation of the delegate methods must take this into account—see
Changes are not reflected until after the controller’s managed object context has received a
process message. Therefore, if you change the value of a managed object’s attribute so that its location in a fetched results controller’s results set would change, its index as reported by the controller would typically not change until the end of the current event cycle (when
process is invoked). For example, the following code fragment would log “same”:
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:
Handling Object Invalidation
When a managed object context notifies the fetched results controller that individual objects are invalidated, the controller treats these as deleted objects and sends the proper delegate calls.
It’s possible for all the objects in a managed object context to be invalidated simultaneously. (For example, as a result of calling
reset(), or if a store is removed from the the persistent store coordinator.) When this happens,
NSFetched does not invalidate all objects, nor does it send individual notifications for object deletions. Instead, you must call
perform to reset the state of the controller then reload the data in the table view (
iOS Version Issues
There are several known issues and behavior changes with
NSFetched on various releases of iOS.
iOS 4.0 and Later
On iOS 4.0 and later,
NSFetched does not silently correct results if you reuse the same cache for multiple controllers.
On iOS 4.0 and later,
NSFetcheddoes not perform some checks that would detect when you erroneously use the same cache for multiple controllers. (This derives from an optimization that can help avoid complex string matching on launch.) If you reuse the same cache for multiple controllers, you will get incorrect results.
iOS 3.2 and Later
On iOS 3.2 and later, if the cache is stale or
nil, the controller attempts to calculate the section information directly in the database instead of fetching the objects. This isn't possible if the
section includes any properties that are not persistent. In that case, the controller will fetch the objects to compute the sections.
Prior to iOS 4.0, there are a number of known issues with delegates handling callbacks. In many cases, you should just reload the associated table view.
instead of per-row updates. For the best user experience, you are encouraged to check the OS version number and use the finer grained delegate methods only on devices running iOS 4.0 and later.
NSFetched does not support sections being deleted as a result of a UI-driven change.
You create a subclass of this class if you want to customize the creation of sections and index titles. You override
section if you want the section index title to be something other than the capitalized first letter of the section name. You override
section if you want the index titles to be something other than the array created by calling
section on all the known sections.