Академический Документы
Профессиональный Документы
Культура Документы
Data Management
2009-09-09
Apple Inc. 2009 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. The Apple logo is a trademark of Apple Inc. Use of the keyboard Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Every effort has been made to ensure that the information in this document is accurate. Apple is not responsible for typographical errors. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Cocoa, Mac, Objective-C, and Xcode are trademarks of Apple Inc., registered in the United States and other countries. iPhone is a trademark of Apple Inc. Simultaneously published in the United States and Canada.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY.
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.
Contents
Introduction
Introduction 7
Organization of This Document 8
Chapter 1
Starting Out 9
Create the Project 10 Understanding a Core DataBased Project 10 The Core Data Stack 11 Managed Objects and the Managed Object Context 11 The Managed Object Model 12 Persistent Store Coordinator 13
Chapter 2
Chapter 3
Chapter 4
Adding Events 25
Implementing the addEvent Method 25 Get the Current Location 25 Create and Configure the Event object 25 Save the New Event 26 Handling Errors 26 Update the Events Array and the Table View 27
3
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
CONTENTS
Displaying Events in the Table View 27 Build and Test 28 Core Data Recap 29 Chapter 5
Fetching Events 31
Fetching Managed Objects 31 Creating and Executing the Request 32 Create the Request 32 Set the Sort Descriptor 32 Execute the Request 33 Finish Up 33 Build and Test 33 Core Data Recap 33
Chapter 6
Deleting Events 35
Deleting Managed Objects 35 Deleting an Event 35 Build and Test 36 Core Data Recap 36
Chapter 7
Next Steps 37
Where to Go from Here 37 The Core Data Utility Tutorial 37 Use a Fetched Results Controller 37 Creating a Managed Object Model with Xcode 37 A Drill-Down Interface 38 Add an Add Sheet 38
4
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
Figures
Chapter 1
Starting Out 9
Figure 1-1 Figure 1-2 Figure 1-3 Figure 1-4 A simple Core Data stack 11 Managed objects in a context, and a table in the persistent store 12 An entity description, a table in the database, and a managed object. 12 A complex Core Data stack 14
5
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
FIGURES
6
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
Core Data is a schema-driven object graph management and persistence framework. Fundamentally, Core Data helps you to save model objects (in the sense of the model-view-controller design pattern) to a file and get them back again. This is similar to archiving (see Archives and Serializations Programming Guide for Cocoa), but Core Data offers much more than that. Amongst other things, it:
Provides an infrastructure for managing all the changes to your model objects. This gives you automatic support for undo and redo, and for maintaining reciprocal relationships between objects. Allows you to keep just a subset of your model objects in memory at any given time. This is especially important on iPhone where conserving memory is critical. Uses a schema to describe the model objects. You define the principal features of your model classesincluding the relationships between themin a GUI-based editor. This provides a wealth of basic functionality for free, including setting of default values and attribute value validation. Allows you to maintain disjoint sets of edits of your objects. This is useful if you want to, for example, allow the user to make edits in one view that may be discarded without affecting data displayed in another view. Has an infrastructure for data store versioning and migration. This lets you easily upgrade an old version of the users file to the current version.
Core Data is available on iPhone OS v3.0 and later. This document describes tools and techniques for iPhone OS v3.0. You should read this document to learn how to use Core Data on iPhone, including:
The fundamental design patterns and techniques that underlie Core Data The basics of using the Xcode data modeling tool How to create, update, and delete objects managed by Core Data, and how to commit changes to a data store
7
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
Important: Core Data is not an entry-level technology. Before starting to use Core Data, you must understand the basics of iPhone application development, including:
How to use Xcode and Interface Builder Fundamental design patterns such as model-view-controller and delegation How to use view controllers, navigation controllers, and table views
None of these tools and techniques are explained in this tutorial, so that the content can focus on Core Data itself. Documents you should read to gain adequate experience include:
Your First iPhone Application Xcode Workspace Guide Cocoa Fundamentals Guide View Controller Programming Guide for iPhone OS Table View Programming Guide for iPhone OS
Starting Out (page 9) The Table View Controller (page 15) Managed Object and Model (page 21) Adding Events (page 25) Fetching Events (page 31) Deleting Events (page 35) Next Steps (page 37)
The source code for the tutorial is provided in the Locations sample code.
CHAPTER 1
Starting Out
The goals of this chapter are to describe the application that you will build, then to create the Xcode project and to understand the basics of what the Xcode project template gives you. The goal of this tutorial is to provide a practical introduction to the Core Data framework and how you use it. The aim here is not to create a polished application, but rather to illustrate the fundamental classes, tools, and techniques youll use in any Core Databased program. It doesnt provide in-depth explanations of all the features the framework offers, but it does give references to other documents you can read to gain a deeper understanding. To add a bit more interest, the tutorial also makes use of the Core Location framework. The Core Location manager is a very straightforward object, and for the purposes of this project, you dont need to understand it in any detail. The application you create is conceptually simpleit lets you record your location at any time as an event, and uses a table view to show the time, latitude, and longitude of all the events youve recorded. It has an Add button to add a new event, and an Edit button that allows you to delete events from the list. In this tutorial, you use Core Data primarily to represent the Event objects and store them in an external file so that they can be displayed when the application launches.
9
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
CHAPTER 1
Starting Out
Note: As a convention, >> denotes the beginning of a paragraph (sometimes including the following bulleted list) that contains steps that you must perform in the tutorial. In code listings, comments included in Xcode template files are not shown.
An application delegate class A MainWindow interface (.xib) file A Core Data model (.xcdatamodel) filetypically referred to as the managed object model
The application also links against the Core Data framework. Of the resources, the first two should be familiar, although the details of the delegate class will be new. The model file is described later in Managed Object and Model (page 21). For now, examine the header file of the application delegate class. In addition to the standard window and view controller, it provides four other properties and a new method:
- (IBAction)saveAction:sender; @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel; @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator; @property (nonatomic, readonly) NSString *applicationDocumentsDirectory;
As its name implies, the applicationDocumentsDirectory property simply returns the path to the applications documents directory, which is where the file containing the applications data will be located. Similarly, the save action method saves the applications data to disk. Saving is discussed in greater detail throughout this document. The remaining properties provide access to whats called the Core Data stack.
10
CHAPTER 1
Starting Out
Persistent Store Coordinator A collection of stores Persistent Object Store A collection of object data
Store File
The objects you usually work directly with are at the top of the stackthe managed object context and the managed objects it contains.
11
CHAPTER 1
Starting Out
Figure 1-2 (page 12) illustrates a managed object context that contains two managed objects corresponding to two records in an external database. In one of the objects, a property value has been changed in memory, but the change has not been committed to the database. Figure 1-2 Managed objects in a context, and a table in the persistent store
Managed Object Context Employee name Fred salary 90000 Employee name Nigel salary 60000
Unsaved data
Employee name salary Fred 90000 Juli 97000 Nigel 50000 Tanya 56000
Current data
Entity Description
Managed Object
12
CHAPTER 1
Starting Out
Core Data uses the model to map between managed objects in your application and records in the database. Its important to be aware that if you change the schema in your application, Core Data wont be able to read stores you created using the previous model. (This is something common to many persistence mechanisms. Core Data, though, does also provide an infrastructure for managing such changessee the Core Data Model Versioning and Data Migration Programming Guide.)
13
CHAPTER 1
Starting Out
Figure 1-4
Customer
14
CHAPTER 2
The goal of this chapter is to create an initial implementation of the table view controller, and to update the application delegate to create and configure an instance of the table view controller. This chapter sets up the table view, creating an instance of a navigation controller and a table view controller, and configuring the Core Location manager. This provides the architecture for the application. In the next chapter, youll use Core Data to manage the actual data. Its assumed that youre already familiar with view controllers and table views; this chapter does not provide significant detail or explanation beyond that you need to understand the role of each of the components in the application. If any of this is too challenging, you should stop here and practice writing some more applications before continuing. The application delegate is responsible for creating, configuring, and displaying a navigation controller and a table view controller. The table view controller displays the array of event objects. To support this, the controller adds four properties to the basic table view controller:
A mutable array, which contains the collection of event objects that the table view controller displays. Its populated from the applications persistent store when the application starts up, and updated as the user adds and removes events. A managed object context, which serves as your gateway to the Core Data stack. A Core Location manager, which provides location information to the application. The user can add new events only when this is active (the iPhone Simulator simulates activity so you dont need to install the application on a device to test it). A bar button item, which the user needs to add events. You need a reference to the button so you can conditionally enable and disable it in response to changes in the Core Location managers state.
15
CHAPTER 2
@interface RootViewController : UITableViewController <CLLocationManagerDelegate> { NSMutableArray *eventsArray; NSManagedObjectContext *managedObjectContext; CLLocationManager *locationManager; UIBarButtonItem *addButton; } @property (nonatomic, retain) NSMutableArray *eventsArray; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain) CLLocationManager *locationManager; @property (nonatomic, retain) UIBarButtonItem *addButton; @end
Synthesize the properties you declared. Implement viewDidLoad to set up the Core Location manager and the Add and Edit buttons. Write the accessor method for the Core Location manager and implement two of its delegate methods. Implement methods to take care of memory management.
All the code described in the following sections goes into the @implementation block of the RootViewController class, replacing implementations provided by the template as appropriate.
16
CHAPTER 2
locationManager = [[CLLocationManager alloc] init]; locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; locationManager.delegate = self; return locationManager; }
Next, implement two delegate methods to enable and disable the Add button as appropriate. If the Core Location manager is generating updates, then enable the button; if the Core Location manager is failing, then disable the button. >> Add the following two Core Location manager delegate methods:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { addButton.enabled = YES; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { addButton.enabled = NO; }
Implementing viewDidLoad
The viewDidLoad method needs to set up the Core Location manager and the Add and Edit buttons. >> Replace the implementation of viewDidLoad with the following:
- (void)viewDidLoad { [super viewDidLoad]; // Set the title. self.title = @"Locations"; // Set up the buttons. self.navigationItem.leftBarButtonItem = self.editButtonItem; addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addEvent)]; addButton.enabled = NO; self.navigationItem.rightBarButtonItem = addButton; // Start the location manager. [[self locationManager] startUpdatingLocation]; }
17
CHAPTER 2
Import the RootViewControllers header file. Synthesize the navigationController property. In the applicationDidFinishLaunching: method, create an instance of RootViewController and a navigation controller to contain it. You also need to pass the applications managed object context to the new root view controller.
18
CHAPTER 2
>> Before the @implementation block of the application delegate class, import the RootViewController classs header file:
#import "RootViewController.h"
>> In the @implementation block of the application delegate class, synthesize the navigation controller property:
@synthesize navigationController;
>> Replace your application delegates applicationDidFinishLaunching: method with the following implementation:
- (void)applicationDidFinishLaunching:(UIApplication *)application { // Configure and show the window. RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain]; NSManagedObjectContext *context = [self managedObjectContext]; if (!context) { // Handle the error. } // Pass the managed object context to the view controller. rootViewController.managedObjectContext = context; UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController]; self.navigationController = aNavigationController; [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; [rootViewController release]; [aNavigationController release]; }
19
CHAPTER 2
The Add button will initially be disabled, but after a few seconds it should become enabled (as the location manager starts sending events). If you tap it, the application will of course crash since you havent yet implemented the addEvent method. Before you can add an event, though, you need to define the Event entity. Thats what youll do next.
20
CHAPTER 3
The goal of this chapter is to allow users to create a new event when they tap the Add button. To do this, you need to define the Event entity in the managed object model, implement the corresponding class, and create an instance of the class in the add method.
21
CHAPTER 3
Theres an important difference between the name of the entity and the name of the Objective-C class used to represent instances of the entity. Core Data uses the entity description to find out about the data objects it manages, so the class name doesnt have to be the same as the entity name. Indeed, in some cases several entities may be represented by the same classNSManagedObject. Core Data is able to differentiate the instances on the basis of their associated entity description.
22
CHAPTER 3
>> Select both the new attributes in the property pane, then in the detail pane select Double from the Type pop-up menu. >> Select just the first new attribute in the property pane, and in the detail pane change the Name of the attribute to latitude. >> Select just the second new attribute in the property pane, and in the detail pane change the Name of the attribute to longitude. Your model should look similar to this:
23
CHAPTER 3
You should see the Entity selection pane, with the Event entity selected. The Generate accessors and Generate Objective-C 2.0 properties options should also be selected. >>Click Finish to generate the files. The Event class interface and implementation files are created and added to your project. There are a few things to notice:
In the interface file (Event.h), all the attributes are represented by object values. Although you specified the latitude and longitude attribute types as Double, the property values at runtime are instances of NSNumber. Core Data uses objects to represent values.
In the implementation file (Event.m), the properties are implemented as dynamic. Normally you might expect to see synthesized, however Core Data generates the accessor methods at runtime.
In the implementation file (Event.m), there is no dealloc method. Normally you might expect to see a dealloc method to release instance variables, however Core Data is responsible for the life-cycle of all modeled properties of a managed object. (If you add your own instance variables that do not have corresponding properties in the managed object model, then you need to manage those yourself as normal.)
The model is also updatedthe Event entity is now represented by the Event class. Because the model was changed, you need to save it.
>>Save the model file. Finally, because the table view controller is going to make use of the new class, import its header file in the table view controllers implementation file. >>In the table view controllers implementation file (RootViewController.m), after the initial import statement, add:
#import "Event.h"
24
CHAPTER 4
Adding Events
The goal of this chapter is to create the application logic to allow the user to create new event objects and display them in the user interface.
Get the current location Create an Event object and configure it using the current location information Save the Event object Update the events array and the user interface
First, though, declare the addEvent method. >> Add a declaration of the addEvent method to the RootViewController header file:
- (void)addEvent;
25
CHAPTER 4
Adding Events
specify, inserted into the managed object context. (For more about the initialization process , see Managed Objects in Core Data Programming Guide). After youve created the object, you can set its property values using accessor methods, just as you would any other object. You get the latitude and longitude from the location as scalar values, so you need to convert these to NSNumber objects for the Event object. You could get the time stamp from the location as well, but this is a constant value on the simulator. Instead, here you can use date method of NSDate to get a date object representing the current date and time. >> Add the following code at the end of the current implementation of addEvent:
// Create and configure a new instance of the Event entity Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext]; CLLocationCoordinate2D coordinate = [location coordinate]; [event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]]; [event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]]; [event setCreationDate:[NSDate date]];
In common with several Core Data methods, the NSManagedObjectContext save: method takes an error parameter and returns a Boolean value to indicate success or failure. The situation is really no different from that in any other application; its just that the return value from the save: method and the error parameter tend to bring into sharper focus the possibility of a problem occurring.
Handling Errors
Its up to you to decide how you handle a Core Data error. In a scenario as simple as that described in Save the New Event (page 26)where the only change you expect is the addition of a single objectif the data cant be saved its likely to be indicative of some sort of catastrophic failure from which recovery might be difficult or impossible. In this situation you might just present an alert sheet telling the user to restart the application.
26
CHAPTER 4
Adding Events
In a more complex scenario, the user might have changed property values, or added or deleted managed objects in such a way that either an individual object is in an inconsistent state (validation fails) or the object graph as a whole is inconsistent. If you have more than one managed object context, its also possible that the persistent store was updated when changes made in a different context were committed and so the objects in the current context are inconsistent with the corresponding records in the store. In general, you can interrogate the error object to find out what went wrong. You should think carefully about what the user experience should be in the event of an error occurring. What information should you present to the user? What options might you give them for recovering from the problem? These are not questions that Core Data is able to answer.
The next task is to complete the implementation of the table view data-source methods to display the events.
Next, you need to configure the table view cells to display information about each event. Youll see there is a nontrivial amount of code, but most of it is related to user interface and display rather than data management. >> Replace the implementation of tableView:(UITableView *)tableView cellForRowAtIndexPath: with the following:
27
CHAPTER 4
Adding Events
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // A date formatter for the time stamp static NSDateFormatter *dateFormatter = nil; if (dateFormatter == nil) { dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; } // A number formatter for the latitude and longitude static NSNumberFormatter *numberFormatter = nil; if (numberFormatter == nil) { numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; [numberFormatter setMaximumFractionDigits:3]; } static NSString *CellIdentifier = @"Cell"; // Dequeue or create a new cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row]; cell.textLabel.text = [dateFormatter stringFromDate:[event creationDate]]; NSString *string = [NSString stringWithFormat:@"%@, %@", [numberFormatter stringFromNumber:[event latitude]], [numberFormatter stringFromNumber:[event longitude]]]; cell.detailTextLabel.text = string; return cell; }
28
CHAPTER 4
Adding Events
If you build and run now, you should find that if you tap the Add button new events are displayed in the table view. If you quit and relaunch the application, though, you wont see the list of Events when it starts up. To remedy this, you need to populate the events array on launch with the existing Event objects. This is your task in the next chapter. Before doing that, restore the project to its pre-testing state. >> Delete the line you added for testing.
You typically create a new managed object using the convenience method insertNewObjectForEntityForName:inManagedObjectContext: of NSEntityDescription. This method ensures that you get a properly initialized instance of the class that represents the entity you specify.
To commit changes to the persistent store, you need to save the managed object context. The context acts as a scratch pad; if you add or modify objects, the changes are held in memory until you invoke save:. Its up to you to decide how to deal with any error that might occur during a save operation.
You get and set a managed objects property values using accessor methods, just as you would any other object. You can also use key-value coding, just as you would any other object, but using accessor methods is much more efficient (see Using Managed Objects in Core Data Programming Guide).
29
CHAPTER 4
Adding Events
30
CHAPTER 5
Fetching Events
The goal of this chapter is to fetch existing Event objects when the application launches.
Array Query Response Persistent Object Store name salary Managed Object Fred 97000
name salary
Unless you really need all the objects of a particular entity, you should use a predicate to limit the number of objects returned to those youre actually interested in. (If youre displaying objects in a table view, you can also use a fetched results controllerNSFetchedResultsControllerto manage a result set for you. It works hard to ensure that as little data as possible is held in memory.)
31
CHAPTER 5
Fetching Events
Note that you dont always need to execute a fetch to retrieve objects. Core Data, if necessary, automatically retrieves objects that are at the destination of a relationship. For example, if you execute a fetch to retrieve an Employee object, then ask it for its related Department, then Core Data fetches the Department for you if it hadnt already been fetched.
The method of interest here is NSEntityDescriptions entityForName:inManagedObjectContext:. You provide the name of the entity you want and the managed object context youre dealing with; the method then asks for the (managed object) contexts (persistent store) coordinators (managed object) model and retrieves from that the entity with the name you specified (you can refer back to The Core Data Stack (page 11) to see a pictorial representation). Conceptually its not very difficult (you just navigate down the stack), and you could do it yourself easily enough, but its much more convenient to use the class method.
32
CHAPTER 5
Fetching Events
(Its often useful to use the initWithObjects: method of NSArray in case you want to add more sort descriptors later.)
As previously, this example leaves it up to you to decide how to handle any error (see Handling Errors (page 26)).
Finish Up
The final steps are to set the view controllers events array instance variable and to release objects that were allocated. >> Add the following code at the end of the current implementation of viewDidLoad:
[self setEventsArray:mutableFetchResults]; [mutableFetchResults release]; [request release];
You fetch managed objects by creating a fetch request. As a minimum, you need to specify an entity. You get the entity using the convenience method entityForName:inManagedObjectContext: of NSEntityDescription. You might also specify a predicate and an array of sort orderings.
33
CHAPTER 5
Fetching Events
To ensure that you retrieve no more objects than necessary (and so keep memory usage down), you should typically try to constrain your request as narrowly as possible using a predicate.
You dont always need to explicitly fetch managed objects. This wasnt addressed directly in code, since there are no relationships in this tutorial. To repeat the point made earlier, though: Core Data, if necessary, automatically retrieves objects that are at the destination of a relationship. For example, if you execute a fetch to retrieve an Employee object, then ask it for its related Department, Core Data fetches the Department for you if it hasnt already been fetched.
34
CHAPTER 6
Deleting Events
The goal of this chapter is to allow the user to delete events from the list.
Deleting an Event
To handle deletion, you implement the table view data source method tableView:commitEditingStyle:forRowAtIndexPath:. It needs to do three things: 1. 2. 3. Delete the selected object. Update the table view. Save the changes.
It should do this only if the action is a delete. >> In the RootViewController implementation file, implement the tableView:commitEditingStyle:forRowAtIndexPath: method as follows:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the managed object at the given index path. NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row]; [managedObjectContext deleteObject:eventToDelete]; // Update the array and table view. [eventsArray removeObjectAtIndex:indexPath.row];
35
CHAPTER 6
Deleting Events
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; // Commit the change. NSError *error; if (![managedObjectContext save:&error]) { // Handle the error. } } }
Created an entity in a managed object model. You also created a custom class to represent the entity. Created an instance of a managed object. You also changed some of its property values. Fetched managed objects. Deleted a managed object.
You may have noticed that, in performing these tasks, the only object in the Core Data stack (see The Core Data Stack (page 11)) with which you interacted directly was the managed object context. Although you have access to the other objects in the stack, you often dont need to use them directly. Either the Xcode template takes care of setting them up, or you use a convenience class method to accomplish a particular task that would otherwise require you to access them.
36
CHAPTER 7
Next Steps
The goal of this chapter is to suggest what steps you might take next to enhance your understanding of Core Data and how you can use it in future applications.
37
CHAPTER 7
Next Steps
A Drill-Down Interface
Extend the Locations application to provide a drill-down interface to allow users to inspect an eventperhaps to edit comments or a add photograph. You need to add more properties to the Event entity, and perhaps a second entity. The TaggedLocations sample provides an example of using a second entity with a to-many relationship. If you add a photograph, consider the memory management implications of fetching a photograph with every Event you retrieve from the store. Core Data has a feature called faulting (see Managed Objects in Core Data Programming Guide) which means that it doesnt have to complete the object graph. You would typically model the photograph as a separate entity, with a relationship from the Event entity to the Photo entity (and a reciprocal relationship from the photo to the event) When you retrieve just a single Event object, the photo relationship may be represented by a fault. If you ask an event for its photo, Core Data automatically fulfills the fault and retrieves the corresponding data for you. See PhotoLocations for an example.
38
A Drill-Down Interface
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
REVISION HISTORY
This table describes the changes to Core Data Tutorial for iPhone OS. Date 2009-09-09 2009-06-04 2009-03-19 Notes Corrected links to sample applications. Corrected typographical errors. Added a missing line of code to the implementation of applicationDidFinishLaunching:. First version of a tutorial that introduces application development for iPhone using Core Data.
2009-03-15
39
2009-09-09 | 2009 Apple Inc. All Rights Reserved.
REVISION HISTORY
40
2009-09-09 | 2009 Apple Inc. All Rights Reserved.