How to retrieve a Managed Object in Core Data Fetch Requests

Retrieving Managed Objects is somewhat more complex than creating them, mainly because you can filter what you’re getting back rather than retrieve everything that your store file has to offer.

Let’s first illustrate a basic NSFetchRequest. For the following examples I’m using the iOS Master/Detail template which provides an Entity called Event with a property called timeStamp. I’ve created custom subclasses for this entity. Press the add button a few times so we have some data, then quit the application.

Basic Fetch Request

Here’s how we can retrieve all our values using a basic Fetch Request:


The easiest way to get this code is by using a code snippet from the Xcode library (search for fetch, the first one is a “basic fetch”).

Note that the results are unfiltered, which means they’re not necessarily in the order you would like them to be in. To remedy this, you can use a Sort Descriptor:

Fetch Request with Sort Descriptors

You can pass more than one Sort Descriptor, hence we need to pass an NSArray to the fetch request. A usage example would be “list all employers alphabetically, in order of which they’ve started working”. To do this, create another sort descriptor, then add both to the array.

The easiest way to get this is to use the Xcode Code Snippets again, this time select the “fetch with sorting” and it will have all this code ready for you.

Fetch Request using a Predicate

Predicates are filters with which you can specify conditions, such as “is this date older than x”, “does the first name contain steve”, and so forth. I have written a more in-depth article on Predictates elsewhere on this site and won’t go into the details.

Here’s how you create a Fetch Request with a Predicate, combined with a Sort Descriptor:


If you don’t need the Sort Descriptor, just remove that code from the example. This snippet is also available from Xcode and is called “fetch with predicate”.

For more information on Predicates, check out Apple’s Predicate Programming Guide.


About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.