NSFetchedResultsController Tutorial: The Easiest Way to Manage Data

If you have heard about NSFetchedResultsController Class for the first time, it is a class with which you can optimize your iOS app to improve response time and reduce the memory overhead.

Presently, most of the developers load all of the FailedBanksInfo objects from the database into memory at once. It is fine and good for the app, but when you’ll have the complex amount of data to load, this process will be slower and it could have a detrimental impact on the users. And, this is where the NSFetchedResultsController class comes to the picture!

Why NSFetchedResultsController Class?

You can easily add it with the Core Data which dramatically improves the performance.

In this tutorial, we’re going to guide you how you can use NSFetchedResultsController class including NSFetchRequest example.

Steps

1. Create an App “SOCoreDataDemo” and select “Use Core Data” during this process.

2. It will create .xcdatamodeld file in app and you can see “Core Data Stack” code in “AppDelegate”

3. Go to SOCoreDataDemo.xcdatamodeld and create an Entity.

4. Now right click on “SOCoreDataDemo” folder and click on “New File”
and choose template from “Core Data” -> “NSManagedObject subclass”

5. Then follow one by one steps, in the end of that you will get two model classes which contain Entity name like (“Student+CoreDataProperties.swift” and “Student.swift”)

6. To import core data, add import statement

import UIKit
import CoreData

7. Add the NSFetchedResultsControllerDelegate protocol to your class.

8. Create object of “NSFetchedResultsController” and “NSManagedObjectContext” in “ViewController.swift”

Once, after completing all the steps, when you compile and run your project, you’ll see the same thing, but if you examine the debug output, you’ll see something different in the behind the scenes.

The NSFetchedResultsController class of your project is getting a list of IDs from FailedBankInfo in a sorted order and when the user goes through the table, it’ll load one batch at a time, rather than loading the entire database of objects into memory at once. This is how Core Data can save plenty of time and increase the performance.