Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

CHAPTER 13: Basic Data Persistence

479

NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entityDescr = [NSEntityDescription

entityForName:@"EntityName" inManagedObjectContext:context]; [request setEntity:entityDescr];

Optionally, you can also specify criteria for a fetch request using the NSPredicate class. A predicate is similar to the SQL WHERE clause and allows you to define the criteria used to determine the results of your fetch request. Here is a simple example of a predicate:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", nameString]; [request setPredicate: pred];

The predicate created by the first line of code tells a fetch request that, instead of retrieving all managed objects for the specified entity, retrieve just those where the name property is set to the value currently stored in the nameString variable. So, if nameString is an NSString that holds the value @"Bob", we are telling the fetch request to bring back only managed objects that have a name property set to "Bob". This is a simple example, but predicates can be considerably more complex and can use Boolean logic to specify the precise criteria you might need in most any situation.

NOTE: Learn Objective-C on the Mac by Mark Dalrymple and Scott Knaster (Apress, 2009) has an entire chapter devoted to the use of NSPredicate.

After you’ve created your fetch request, provided it with an entity description, and optionally given it a predicate, you execute the fetch request using an instance method on NSManagedObjectContext:

NSError *error;

NSArray *objects = [context executeFetchRequest:request error:&error]; if (objects == nil) {

// handle error

}

executeFetchRequest:error: will load the specified objects from the persistent store and return them in an array. If an error is encountered, you will get a nil array, and the error pointer you provided will point to an NSError object that describes the specific problem. Otherwise, you will get a valid array, though it may not have any objects in it, since it is possible that none meet the specified criteria. From this point on, any changes you make to the managed objects returned in that array will be tracked by the managed object context you executed the request against, and saved when you send that context a save: message.

The Core Data Application

Let’s take Core Data for a spin now. First, we’ll return our attention to Xcode and create our data model.

www.it-ebooks.info

480

CHAPTER 13: Basic Data Persistence

Designing the Data Model

Select Core_Data_Persistence.xcdatamodel to open Xcode’s data model editor. The data model editing pane shows all the entities, fetch requests, and configurations that are contained within your data model.

NOTE: The Core Data concept of configurations lets you define one or more named subsets of the entities contained in your data model, which can be useful in certain situations. For example, if you want to create a suite of apps that share the same data model, but some apps shouldn’t have access to everything (perhaps there’s one app for normal users and another for sysadmins), this approach lets you do that. You can also use multiple configurations within a single app as it switches between different modes of operation. In this book, we’re not going to deal with configurations at all, but since the list of configurations (including the single default configuration that contains everything in your model) is right there, staring you in the face beneath the entities and fetch requests, we thought it was worth a mention here.

As shown in Figure 13–6, those lists are empty now, because we haven’t created anything yet. Remedy that by clicking the plus icon labeled Add Entity in the lower-left corner of the entity pane. This will create a brand-new entity with the name Entity (see Figure 13–7).

Figure 13–7. The data model editor, showing our newly added entity

www.it-ebooks.info

CHAPTER 13: Basic Data Persistence

481

As you build your data model, you’ll probably find yourself switching between Table view and Graph view using the control at the bottom right of the editing area. Switch to Graph view now. Graph view presents a little box representing our entity, which itself contains sections for showing the entity’s attributes and relationships, also currently empty (see Figure 13–8). Graph view is really useful if your model contains multiple entities, since it shows a graphic representation of all the relationships between your entities.

Figure 13–8. Using the control in the lower-right corner, we switched the data model editor into Graph mode. Note that Graph mode shows the same entities as Table mode, just in a graphic form. This is useful if you have multiple entities with relationships between them.

NOTE: If you prefer working graphically, you can actually build your entire model in Graph view. We’re going to stick with Table view in this chapter because it’s easier to explain. When you’re

creating your own data models, feel free to work in Graph view if that approach suits you better.

Whether you’re using Table view or Graph view for designing your data model, you’ll almost always want to bring up the Core Data data model inspector. This inspector lets you view and edit relevant details for whatever item is selected in the data model editor—whether it’s an entity, attribute, relationship, or anything else. You can browse an existing model without the data model inspector, but to really work on a model, you’ll invariably need to use this inspector, much like you frequently use the attributes inspector when editing nib files.

www.it-ebooks.info

482 CHAPTER 13: Basic Data Persistence

Press Style for menu shortcut to open the data model inspector. At the moment, the inspector shows information about the entity we just added. Change the Name field from Entity to Line (see Figure 13–9).

Figure 13–9. Using the data model inspector to change our entity’s name to Line

If you’re currently in Graph view, switch to Table view now. Table view shows more details for each piece of the entity we’re working on, so it’s usually more useful than Graph view when creating a new entity. In Table view, most of the data model editor is taken up by the table showing the entity’s attributes, relationships, and fetched properties. This is where we’ll set up our entity.

Notice that at the lower right of the editing area, there’s an icon containing a plus sign, similar to the one at the lower left, which you used to create the entity. If you select your entity, and then click the plus sign and hold down the mouse button, a popup menu will appear, allowing you to add an attribute, relationship, or fetched property to your entity (see Figure 13–10).

www.it-ebooks.info

CHAPTER 13: Basic Data Persistence

483

NOTE: Notice that you don’t need to press and hold to add an attribute. You’ll get the same result

if you click the plus icon. Shortcut!

Figure 13–10. With an entity selected, press and hold the right plus sign icon to add an attribute, relationship, or fetched property to your entity.

Go ahead and use this technique to add an attribute to your Line entity. A new attribute, creatively named attribute, is added to the Attributes section of the table and selected. In the table, you’ll see that not only is the row selected, but the attribute’s name is selected as well. This means that immediately after clicking the plus sign, you can start typing the name of the new attribute without further clicking.

Change the new attribute’s name from attribute to lineNum, and click the popup next to the name to change its Type from Undefined to Int16, which turns this attribute into one that will hold an integer value. We will be using this attribute to identify for which of the four fields the managed object holds data. Since we have only four options, we selected the smallest integer type available.

Now direct your attention to the data model inspector, where additional details can be configured. The checkbox below the Name field on the right, Optional, is selected by

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]