Core Data Guide

Core Data Fetch Request Template

Rajai Kumar
Nerd For Tech
Published in
3 min readFeb 21, 2021

--

developer.apple.com

Fetch request templates are one of the most underrated and under used features in Core Data. It helps you to set conditions for the attributes in your entity to filter the data according to your needs.

Enough with the grass hopper speech, let’s see an example.

We have a Fight Club app made for this tutorial.

This app has an entity called Member and it has two attributes name & occupation.

We are going to create a fetch request by long pressing the Add Entity button at the bottom of the .xcdatamodel file.

Form the sub menu, press the Add Fetch Request option.

A fetch request will be created and name it appropriately. I’m going to name it as Doctors, because this fetch request will help me filter the members whose occupation is doctor. Press the + button on the right and set occupation is Doctor.

Now let’s create another fetch request to filter members whose names start with the letter B.

It’s time for a small task😁.

memegenerator.net

Create two fetch requests one for fetching members whose occupation is Engineer and another to fetch members whose names start with the letter R.

After your task, your Fetch Requests section should look something like this.

Let’s write some code to use the fetch requests we created. First, we are going to create a method which will take the fetch request and provides the data to a NSManagedObject array object.

ray.so

Now use the fetch request template and get the required data.

ray.so

📺 Demo

--

--

Rajai Kumar
Nerd For Tech

I’m a workaholic iOS developer. I focus a lot on UX and product efficiancy.