TweetFollow Us on Twitter

Introduction to Core Data, Part IV

Volume Number: 22 (2006)
Issue Number: 2
Column Tag: Programming

Introduction to Core Data, Part IV

Storing Fetch Requests in your Data Model

by Jeff LaMarche

In the last Core Data article we talked about creating Fetch Requests programmatically using format strings and predicates. Using format strings to create Fetch Requests is a little bit inelegant, although it does give you a tremendous amount of flexibility. For your day-to-day, run-of-the-mill data fetching needs there is an easier way that gets those format strings out of your compiled code. You can create Fetch Requests right in your data model. This month, we're going to take a quick look at doing just that: We're going to build Fetch Requests and predicates right in Xcode and then look at how we get those Fetch Requests from our code.


In Xcode, I went ahead and built a simple data model with a single entity called Person that contains two string attributes called firstName and lastName, and a date attribute called birthDate. I also gave the entity a to-one relationship called spouse that can connect this entity to one other Person entity. I'll be using this simple data model to illustrate my points in the rest of this article. We've already discussed creating data models back in the first part of this series (Intro to Core Data, July, 2005), so I won't be guiding you through creating the data model this month. If you create a new project in Xcode using the Core Data Application project template, you should be able to quickly create the same data model yourself, or you can simply download my project from the MacTech FTP site. You might want to do that before you continue with the article, as I'll be making frequent references to this data model, however it is a simple enough data model that you can probably follow along without it.

Stored Fetch Requests

If you search Apple's documentation for information on how to store Fetch Requests in your data model, you might come to the conclusion that it simply can't be done. The ability to store Fetch Requests as part of the data model, although present in Core Data's predecessor Enterprise Objects Framework, seemed to be absent from the data model editor in Xcode when Core Data was first released. It was actually there, but it just wasn't very obvious; you had to change the view settings for the properties pane in order to see or work with Fetch Requests (Figure 1). The official documentation spends so little time on the topic that it's very easy to miss it.

Figure 1. Getting to the fetch requests stored in your data model.

With the recent release of Xcode 2.1, however, the eagle-eyed among you have probably noticed that a fourth option has been added to the property pane's add (plus sign) pop-up menu in the data model editor (Figure 2). Unlike with earlier releases, this option now shows up regardless of whether you've changed the pane to show Fetch Requests or not. That makes the functionality a little more obvious, and a little easier to access.

Figure 2. You can now add a fetch request when looking at the properties pane in any view mode.

If you decide to store fetch requests in your data model (and you should), you still have to know about predicates and format strings. All that information I gave you in the Core Data III article back in November was not for naught. Without a solid understanding of format strings and predicates, you wouldn't be able to use the functionality we're going to go over this month. See? There is a method to my madness.

The Predicate Builder

The way that we build Fetch Requests in Xcode is to use the Predicate Builder. This is a tool that is built into Xcode's data model editor, and is used for visually creating predicates (and the format string that they're based on). Why don't you go ahead and select the Person entity in your data model, then press the little plus sign in the properties pane (the top-middle pane). Select Add Fetch Request from the menu that pops up (Figure 2). You'll get a new Fetch Request, which you should go ahead and rename to olderThanSpouse in the top right pane. We are going to create a predicate that brings back all people who have a spouse and are older than them.

When you edit the name of this Fetch Request, you should see a button labeled Edit Predicate down below where you change the name. This button will call up the Predicate Builder. The large text field above the Edit Predicate button will show you the format-string associated with any predicate you build with the Predicate Builder. Although it looks like you should be able to edit the format string there, you actually can't, though you can select it and copy to the clipboard.

Figure 3. You can get to the predicate builder by pressing the Edit Predicate button when the fetch request is selected in the properties pane.

Go ahead and click that button to bring up the Predicate Builder. This interface probably looks familiar to you, at least if you've ever set up a rule in Mail, or defined a smart playlist in iTunes or a smart album in iPhoto. Predicates are built using a fairly standard-issue Apple rules interface (Figure 4). Almost. It's a very functional interface, but it's not as intuitive as the ones you've probably used. There's actually a little bit of hidden functionality in there, so let's take a closer look at it.

Figure 4. The Predicate Builder

Starting from the left side, the first thing you'll see is a pop-up menu. This is the key pop-up menu, sometimes simply referred to as the left hand side menu. This is where you define what you're comparing or, in other words, the left side of the format string. Most often, you're going to select one of the attributes of your entity. If you click the pop-up menu, you'll see that you have more options to select from than just the attributes of the current entity, however (Figure 5).

Figure 5. The key pop-up menu.

The top-most item in the menu is labeled Expression. You won't find this option well-documented anywhere unfortunately, but it's a very handy one nonetheless. This option changes the whole line to a single editable text field where you can plug in a format string. Why would you want to do that? Well, there might be times when you need to access a property using key-value coding that the data model editor doesn't know about, perhaps because you've created an attribute and left its type as undefined. Basically, if you know about an attribute that Xcode doesn't know about for any reason, you can use this option to manually enter the format string for one part of the predicate. In practice, you probably won't have to use this very often, but it's good to know it's there in case you ever need it.

The next option, labeled Select Key... brings up a browser to let you select an attribute. This might seem a little redundant, since the individual attributes of this entity are also available right in the pop-up menu, but you might have noticed that the spouse relationship was not accessible there, because it's not an attribute. Although this option can be used just to select an attribute of this entity, the primary reason it exists is so that you can drill down into other entities through this entity's relationships. Let's say we wanted to create a fetch request based on the birthday of the person's spouse. In that case, you could use the Select Key... option, click on the spouse entry in the left-most column, then click on the birthDate field in the second column (Figure 6). Don't actually do that, however. Click the Cancel button; I don't want you to actually select the spouse's birthDate field here.

Figure 6. Selecting attributes of a relationship using the Select Key... option.

The next few options are pretty self-explanatory; they are simply the attributes of this entity that you can select (firstName, lastName, birthDate) The options in the next section below the attributes allow you to add additional criteria to this rule. Here's where we start to see a deviation from the standard-issue Apple rules dialog. In most rules dialogs, such as iTunes' smart playlist dialog (Figure 7), you define a simple list of criteria and choose to require either all of the criteria, or any single criteria in the list.

Figure 7. The smart playlist rules dialog from iTunes.

The Predicate Builder allows you to create much more complex and robust rules than the rule dialogs in Apple's consumer applications. You can use all three of the standard Boolean operators (and, or, not), and choose a different operator for each pair of operations. You can also set precedence by creating a hierarchy of criteria.

The four Add options under the key pop-up menu all insert another criterion into the predicate, and function almost exactly the same. The only difference in the options, is which of the Boolean operators is used, although that can be changed after the fact. The bottom-most Add option is the same as pressing the plus button on the right-hand side of the row or the Add AND option. You can look at Figure 8 to get an idea of the sort of complex rules you can build using the Predicate Builder. The last option on the left-hand side menu simply removes the row and functions exactly like pressing the minus button on the right-hand side of the row.

Figure 8. Crafting a complex Fetch Request in the Predicate Builder.

As we move to the right, the next pop-up menu is the operator to be used for this row. The available operators change depending on the type of attribute selected in the key pop-up menu. Different options are presented, for example, when you select a string attribute than when you select a number or date attribute.

Last, but not least, the next field over is simply the value to be compared when evaluating this criterion. The example in Figure 8 shows a number of comparisons being made, but they're all being made to constant values typed right into this field. That's useful, but not always what you want. To be really useful, you'd need to be able to plug in values at runtime or, perhaps, compare one attribute to another. But there doesn't seem to be any way to enter anything other than a constant here, does there?

Well, here's a bit of hidden functionality. Go ahead and either right-click or control-click in the space to the left of the minus button that's used to delete the row. Lo and behold, you'll be presented with a contextual menu with some new options(Figure 9).

Figure 9. The hidden contextual menu.

The bottom five options are exactly the same as ones you saw in the left-hand key pop-up menu. They add or remove the current row. The top three options, however, are the magic options. They allow you to select the types values for the right-hand side of the equation. The default value, as you've seen, is Constant, which allows you to specify the comparison value right in the Predicate Builder.

Let's skip the second option (Variable) for just a second. We'll come back to it in a moment, but it's more involved than the other two, so let's look at the third option first. Go ahead and select Key. Doing that, will change the place where you used to be able to enter a constant value into another pop-up menu that looks identical to the left-hand side pop-up menu. This is the right-hand side key pop-up menu. This can be useful in many situations. We stated that we were going to create a Fetch Request to retrieve all people who are older than their spouse. Easy enough. Just choose Select Key... from the right-hand side pop-up menu and drill down to the spouse's birthDate as we did a moment ago on the left-hand side. Next, change the operator pop-up menu to greater-than and make sure birthDate is selected in the left-hand key pop-up menu. (Figure 10).

Figure 10. Comparing a key to another key

Go ahead and click the OK button; this Fetch Request is done. You can take a look in the Predicate: field to see the format string you just created. Now, let's create a little more complex Fetch Request. Go ahead and click the plus button in the lower left of the Fetch Request pane (the top-middle pane of the data model editor). When you added a Fetch Request before, the Property pane turned into the Fetch request pane, so this time, you can just click the plus button and don't have to select from a pop-up menu. When the new Fetch Request comes up, rename it to birthDateBetween, then click the Edit Predicate button to get back to the Predicate Builder. We're going to build a Fetch Request to retrieve all people with a birth date between two values, but we don't want to specify those two values until runtime.

Let's now talk about the second option on the contextual menu: Variable. If you control-click to the left of the minus button again and select that option, you'll get an editable text field labeled Variable (Figure 11). This is where the juju happens, baby. In this field, we can specify a variable name and later we'll be able to replace that variable with another value in our code. This is called a substitution variable or sometimes a bind variable. This is what makes stored Fetch Requests flexible enough to use for just about everything. If you specify a value here - which can be just about any string value you wish to use - you will then be able to substitute any other value of your choosing when you retrieve the Fetch Request from your data model.

If you're playing along at home, go ahead and change the operator pop-up menu from = to within, which will add a second row to this criteria. The new row is not a new criteria, but just a second parameter to the existing one. The within operator allows you to search based on a date attribute that falls between two other date values. Control-click to the right of the new row that got entered and change it also to variable. Now, go ahead and assign each of those variables a name. I chose FROMDATE and TODATE, as you can see from Figure 11. Once you've got it set up, click the OK button.

Figure 11. Specifying a substitution variable in Predicate Builder.

After the Predicate Builder is dismissed, go ahead and look at that large text field labeled Predicate:. That will show you the format string that will be used for creating this Fetch Request. Notice the dollar sign in front of FROMDATE and THRUDATE? That's how substitution variables are specified in format strings.

Go ahead and save your data model and let's take a look at how we can pull our Fetch Request out of the data model instead of having to create them from scratch, as we did in the previous article.

Getting Fetch Requests Out Of the Data Model

Technically speaking, you aren't storing a Fetch Request in your data model, even though it's usually referred to that way. Your data model is not like a nib file, where serialized objects are being stored. Instead, what's really happening is you are creating a template from which a new Fetch Request can be instantiate at run time. This is a relatively straight forward process.

One thing that might trip you up is the fact that you don't use NSMangedObjectContext to retrieve your Fetch Requests. If you've been using Core Data for a little while, you've probably gotten accustomed to using the context for retrieving, inserting, and editing your data. A Fetch Request, however, is not data. It's part of your data model. Therefore, instead of using the context, you have to use your managed object model (NSManagedObjectModel) to retrieve your Fetch Requests. Fortunately, the managed object model is available through an accessor method that gets created automatically for you when you use one of the Core Data project templates. In a Core Data Application project, you can get the managed object model using the managedObjectModel method of the application delegate class (applicationName_AppDelegate). In a Core Data document-based application, you use the same method, but call it on your document class instead (which inherits the method from NSPersistentDocument).

Once you have a reference to your managed object model, it's simply a matter of asking it for your Fetch Request by name. If you aren't using substitution variables, it's very easy. Here's how we would get that first Fetch Request we created:

Getting a Fetch Request from your data model

NSManagedObjectModel *model = [self managedObjectModel];
NSFetchRequest *fetch = 
   [model fetchRequestTemplateForName:@"olderThanSpouse"];

That's all there is to that one. After this call, you're ready to fetch data from the context.

On the other hand, if you have specified substitution variables in your Fetch Request, then you have to build a dictionary containing the substitution variable names as the key values, and the values you wish to replace them with as the corresponding objects. In our case, that means creating an NSDictionary with two entries. One with a key value of @"FROMDATE" and another with a key value of @"TODATE". The objects to be passed for both of these keys need to be NSDate object instances since we are comparing with a date field. If we were comparing a numeric field, we'd use NSNumber, and if were comparing a string field, we would use an NSString. Here's an example of getting our second Fetch Request out of the data model:

Getting a Fetch Request with substitution variables

NSManagedObjectModel *model = [self managedObjectModel];
NSDate *fromDate = [NSCalendarDate 
NSDate *toDate = [NSCalendarDate 
NSDictionary *subs = [NSDictionary 
   dictionaryWithObjectsAndKeys:fromDate, @"FROMDATE", 
   toDate, @"TODATE", nil];
NSFetchRequest *fetch = 
   [model fetchRequestFromTemplateWithName:
   @"birthDateBetween" substitutionVariables:subs];

Once either of these two chunks of code fires, you will have a pointer to a Fetch Request. It is exactly the same as if you had created it using a format string and a predicate like we did in the previous article, but with less code and without having the format string inside your compiled application.


Storing the definition of your Fetch Requests inside your data model has many advantages. You can use the Predicate Builder to more easily build complex criteria it allows you to move potentially complex format strings out of your compiled code and into your data model. It also allows you to use bind variables to let you alter your Fetch Requests at runtime based on user-provided data.

These tools provide you with the ability to create and use just about any type of Fetch Request you might need right in your data model, and there is very little reason in most situation not to use it. Unfortunately, the fact that the functionality was sort of squirreled away where it wasn't obvious means it is probably being underused, but now that you where it is and how to use it, you can go ahead and get all those yucky format strings and predicates out of your code.

Jeff LaMarche wrote his first line of code in Applesoft Basic on a Bell & Howell "Darth Vader" Apple ][+ in 1980 and he's owned at least one Apple computer at all times since. In addition to writing, Jeff codes in a variety of languages, with Cocoa Objective-C being, by far, his favorite. Feel free to drop him a line anytime at


Community Search:
MacTech Search:

Software Updates via MacUpdate

NetShade 8.3 - Browse privately using an...
NetShade is an anonymous proxy and VPN app+service for Mac. Unblock your Internet through NetShade's high-speed proxy and VPN servers spanning 17 countries. NetShade masks your IP address as you... Read more
Adobe Animate CC 2020 20.0.1 - Animation...
Animate CC 2020 is available as part of Adobe Creative Cloud for as little as $20.99/month (or $9.99/month if you're a previous Flash Professional customer). Animate CC 2020 (was Flash CC) lets you... Read more
Adobe Acrobat DC 19.021.20058 - Powerful...
Acrobat DC is available only as a part of Adobe Creative Cloud, and can only be installed and/or updated through Adobe's Creative Cloud app. Adobe Acrobat DC with Adobe Document Cloud services is... Read more
Adobe Acrobat Reader 19.021.20058 - View...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more
Adobe Flash Player - Plug-in...
Adobe Flash Player is a cross-platform, browser-based application runtime that provides uncompromised viewing of expressive applications, content, and videos across browsers and operating systems.... Read more
Adobe InDesign CC 2019 15.0.1 - Professi...
InDesign CC 2019 is available as part of Adobe Creative Cloud for as little as $20.99/month (or $9.99/month if you're a previous InDesign customer). Adobe InDesign CC 2019 is part of Creative Cloud.... Read more
Adobe Lightroom Classic 9.1 - Import, de...
You can download Lightroom for Mac as a part of Creative Cloud for only $9.99/month with Photoshop, included as part of the photography package. The latest version of Lightroom gives you all of the... Read more
Shredo 1.2.7 - $6.99
Shredo is a beautiful, functional file-shredding and privacy scan utility. It permanently shreds files, folders, and external volumes' contents to keep information secure and impossible for anyone to... Read more
Visual Studio Code 1.41.0 - Cross-platfo...
Visual Studio Code provides developers with a new choice of developer tool that combines the simplicity and streamlined experience of a code editor with the best of what developers need for their... Read more
calibre 4.6.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more

Latest Forum Discussions

See All

King's Throne, the hugely ambitious...
King's Throne: Game of Lust is a deeply immersive medieval-set idle RPG which sees you playing as an ambitious prince, and sole heir to your father's kingdom. On a seemingly ordinary night whilst wandering the king's castle, you make the shocking... | Read more »
Abyssrium Pole is an upcoming aquarium b...
FleroGames' upcoming Abyssrium Pole has recently hit one million pre-registers, which is very impressive, particularly for a fairly casual looking game. Those who have pre-registered will receive 1000 Pearl when the game launches on 8th January... | Read more »
Two Spies is pretty fun, but it's h...
Two Spies just dropped on the App Store this week, and it looks pretty neat. The game has two players capturing various cities across Europe, with the goal of eventually spotting and striking the other spy down. It may be simple-looking, but after... | Read more »
Two Spies is a turn-based game for iOS t...
There aren't too many games that feature pass and play multiplayer and there are even less where you can only play against people you know, even when playing online. But Two Spies does both of those things and you can get it for iOS right now. [... | Read more »
Solve your way through new low-poly puzz...
The best escape-the-room games don’t just test your creative problem-solving skills – they look great, too. Released in October this year by Antler (the developer of the succesful VR puzzle SVRVIVE: The Deus Helix), Krystopia offers everything you... | Read more »
Get ready for an epic adventure with Pea...
Following a hugely successful pre-registration campaign, Pearl Abyss' much-hyped MMORPG, Black Desert Mobile, has finally arrived for iOS and Android. With some of the most impressive visuals on mobile, a vast open world to explore, an in-depth... | Read more »
Elder Scrolls: Blades has ditched chest...
Elder Scrolls: Blades started out as one of the most hyped mobile games of 2019, boasting some impressive visuals and no shortage of promise. Our hopes were somewhat dashed when it eventually launched and we all became privy to its mishandled... | Read more »
Hands-On with the Pocket City December U...
At the end of last month, Codebrew Games announced an update coming to their popular city-builder, Pocket City some time this month. In this update is the promise of expanding your city out into other regions, enacting policies, and more. The full... | Read more »
Black Desert Mobile is available for pre...
Pearl Abyss' stunning open-world MMORPG, Black Desert Mobile, is set to launch for iOS and Android on December 11th at 12 AM PST (8 AM UTC). However, those looking to get in early and test out the in-depth character customisation will be able to... | Read more »
Extraordinary Ones, NetEase's innov...
NetEase's inventive 5v5 anime MOBA, Extraordinary Ones, has now opened for pre-registration ahead of its global launch in early 2020. The game seems to have received a fairly warm reception from fans after its soft-launch earlier in the year,... | Read more »

Price Scanner via

Apple Watch Series 3 models on sale at Amazon...
Amazon has Apple Watch Series 3 GPS models on sale for $20 off MSRP, starting at only $179. Their prices are the lowest available for these models from any Apple reseller. Choose Amazon as the seller... Read more
Sunday AirPods Sale: Amazon drops prices to a...
Amazon has new 2019 Apple AirPods on sale today ranging up to $30 off MSRP, starting at $139. Shipping is free: – AirPods Pro: $249 $0 off MSRP – AirPods with Wireless Charging Case: $168.95 $30 off... Read more
Holiday 2019 sale: 11″ iPad Pros for up to $2...
Amazon has new Apple 11″ iPad Pros in stock today and on sale for up to $200 off Apple’s MSRP as part of their Holiday 2019 sale. These are the same iPad Pros sold by Apple in its retail and online... Read more
B&H has 12.9″ WiFi iPad Pros on sale for...
B&H Photo has new 12.9″ WiFi iPad Pros on sale for up to $150 off Apple’s MSRP as part of their Holiday 2019 sale. Overnight shipping is free to many addresses in the US: – 12.9″ 64GB WiFi iPad... Read more
Find the best Holiday 2019 prices on Apple’s...
Our Apple award-winning price trackers are the best place to look for the best deals and lowest prices on Apple gear this 2019 Holiday shopping season. Scan our price trackers for the latest... Read more
13″ 2.4GHz/256GB Silver MacBook Pro on sale f...
Amazon has the Silver 13″ 2.4GHz/256GB 4-Core Touch Bar MacBook Pro on sale for $1499.99 shipped. Their price is $300 off Apple’s MSRP, and it’s the lowest price currently available for a 13″ 2.4GHz... Read more
Sams Club one day sales event December 14th:...
Through midnight Saturday night (December 14th), Sams Club online has several Apple Watch Series 5 models on sale for $40 off MSRP as part of their One Day sales event. Choose free shipping or free... Read more
Total Wireless offers iPhone 6S models for as...
Total Wireless has Apple 32GB iPhone 6S models available starting at $99: – 32GB iPhone 6S: $99.99 – 32GB iPhone 6S Plus: $149.99 A no-contract Total Wireless prepaid plan is required with your... Read more
Get a 4 or 6-core Mac Mini for up to $170 off...
B&H Photo has 4-Core and 6-Core Mac minis on sale for up to $170 off Apple’s standard MSRP as part of their Holiday 2019 sale. Overnight shipping is free to many US addresses: – 3.6GHz Quad-Core... Read more
Amazon restocks base 13″ 1.4GHz MacBook Pro f...
Amazon has restocked the base 13″ 1.4GHz/128GB Space Gray MacBook Pro for $1099.99 shipped. Their price is $200 off Apple’s MSRP, and it’s the cheapest price available for a new MacBook Pro. Amazon... Read more

Jobs Board

*Apple* Mobility Sales Professional - Best B...
**750138BR** **Job Title:** Apple Mobility Sales Professional **Job Category:** Store Associates **Store NUmber or Department:** 000471-Mt Vernon-Store **Job Read more
*Apple* Engineering Specialist (ITC ) - Gene...
…Suitability clearance, per contract requirements. Currently, we are seeking an Apple Engineering Specialist in Washington, DC The responsibilities for candidates in Read more
Senior *Apple* Endpoint Engineer - Leidos (...
…Medicaid Service (CMS) End User environment. Perform specific duties as an Apple Endpoint Engineer in support of the infrastructure operations, hardware, software Read more
Perioperative - RN - ( *Apple* Hill Surgical...
Perioperative - RN - ( Apple Hill Surgical Center) Tracking Code 59281 Job Description Monday - Friday - Part Time - Days Possible Saturdays General Summary: Under Read more
Lead DevOps Engineer - *Apple* - Theorem, L...
Job Summary Apple is looking for a seasoned Lead DevOps Engineer that can lead multiple projects and teams while delivering high quality and performant solutions in Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.