an ios 4 iphone core data tutorial (xcode 4) - techotopia

8
11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia 1/8 www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29 1 An iOS 4 iPhone Core Data Tutorial (Xcode 4) From Techotopia Previous Table of Contents Next Working with iOS 4 iPhone Databases using Core Data (Xcode 4) An Overview of iOS 4 iPhone Multitouch, Taps and Gestures (Xcode 4) eBookFrenzy.com Purchase and download the fully updated iOS 5 Edition of this book in Print ($27.99) or eBook ($12.99) format. iPhone iOS 5 Development Essentials Print and eBook (ePub/PDF) editions contain 56 chapters. In the previous chapter, entitled Working with iOS 4 iPhone Databases using Core Data, an overview of the Core Data stack was provided, together with details of how to write code to implement data persistence using this infrastructure. In this chapter we will continue to look at Core Data in the form of a step by step tutorial which implements data persistence using Core Data in an iOS 4 iPhone application. Contents 1 The iPhone Core Data Example Application 2 Creating a Core Data based iPhone Application 3 Creating the Entity Description 4 Adding a View Controller 5 Connecting the View 6 Adding Actions and Outlets to the View Controller 7 Designing the User Interface 8 Saving Data to the Persistent Store using Core Data 9 Retrieving Data from the Persistent Store using Core Data 10 Releasing Memory 11 Building and Running the Example Application The iPhone Core Data Example Application The application developed in this chapter will take the form of the same contact database application used in previous chapters. The objective being to allow the user to enter name, address and phone number information into a database and then search for specific contacts based on the contact’s name. Creating a Core Data based iPhone Application As is often the case, we can rely on Xcode to do much of the preparatory work for us when developing an iPhone application that will use Core Data. Currently, however, only the Navigation-based Application, Utility Application and Window-based Application project templates offer the option to automatically include support for Core Data. To create the example application project, launch Xcode and select the option to create a new project. In the new project window, select the Window-based Ads by Google Xcode Cocoa Iphone Download Iphone App Language Tutorial Like 4 people like this. Be the first of your friends. Database System Get great ideas and insights from business intelligence gurus. Go! www.AllAnalytics.com Free Association Database Easy-To-Use, Secure & Time-Saving. Used By 1000s Of Associations! GroupSpaces.com PowerBasic vs VisualBasic Faster. No Run-Times. No Bloat! CGI, Macros, ASM, Reg Expressions www.powerbasic.com IP Access Control Single door PoE Controller Scale from one to hundreds of doors www.infinias.com Sirius Rental Software Award-winning Rental Software for Equipment, Party & AV rental www.Orion-Soft.com NuoDB - NewSQL Leader Elastic SQL database for the cloud Download the Beta today www.nuodb.com Visual SQL to XML Easy to use Data Mapping environment. Try now! www.ecrion.com

Upload: raulestevez

Post on 18-Apr-2015

192 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

1/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

1

An iOS 4 iPhone Core Data Tutorial (Xcode 4)From Techotopia

Previous Table of Contents NextWorking with iOS 4 iPhoneDatabases using Core Data(Xcode 4)

An Overview of iOS 4 iPhoneMultitouch, Taps and Gestures

(Xcode 4)

eBookFrenzy.com

Purchase and download the fully updated iOS 5 Edition of this book in Print ($27.99) or eBook ($12.99) format.iPhone iOS 5 Development Essentials Print and eBook (ePub/PDF) editions contain 56 chapters.

In the previous chapter, entitled Working with iOS 4 iPhone Databases using Core Data, an overview of the Core Data stack was provided, together with details ofhow to write code to implement data persistence using this infrastructure. In this chapter we will continue to look at Core Data in the form of a step by step tutorialwhich implements data persistence using Core Data in an iOS 4 iPhone application.

Contents1 The iPhone Core Data Example Application2 Creating a Core Data based iPhone Application3 Creating the Entity Description4 Adding a View Controller5 Connecting the View6 Adding Actions and Outlets to the View Controller7 Designing the User Interface8 Saving Data to the Persistent Store using Core Data9 Retrieving Data from the Persistent Store using Core Data10 Releasing Memory11 Building and Running the Example Application

The iPhone Core Data Example ApplicationThe application developed in this chapter will take the form of the same contact database application used in previous chapters. The objective being to allow theuser to enter name, address and phone number information into a database and then search for specific contacts based on the contact’s name.

Creating a Core Data based iPhone ApplicationAs is often the case, we can rely on Xcode to do much of the preparatory work for us when developing an iPhone application that will use Core Data. Currently,however, only the Navigation-based Application, Utility Application and Window-based Application project templates offer the option to automatically includesupport for Core Data.

To create the example application project, launch Xcode and select the option to create a new project. In the new project window, select the Window-based

Ads by Google Xcode Cocoa Iphone Download Iphone App Language Tutorial

Like 4 people like this. Be the first of your friends.

Database SystemGet great ideas and insights from businessintelligence gurus. Go!www.AllAnalytics.com

Free Association DatabaseEasy-To-Use, Secure & Time-Saving. Used By1000s Of Associations!GroupSpaces.com

PowerBasic vs VisualBasicFaster. No Run-Times. No Bloat! CGI, Macros,ASM, Reg Expressionswww.powerbasic.com

IP Access ControlSingle door PoE Controller Scale from one tohundreds of doorswww.infinias.com

Sirius Rental Software Award-winning Rental Software for Equipment, Party & AV rental www.Orion-Soft.com

NuoDB - NewSQL Leader Elastic SQL database for the cloud Download the Beta today www.nuodb.com

Visual SQL to XML Easy to use Data Mapping environment. Try now! www.ecrion.com

Page 2: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

2/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

To create the example application project, launch Xcode and select the option to create a new project. In the new project window, select the Window-basedApplication option. In next screen make sure that the Device Family menu is set to iPhone and that the check box next to Use Core Data is selected. Name theproduct coreData and click Next to select a location to store the project files.

Xcode will create the new project and display the main project window. In addition to the usual files that are present when creating a new project, this time anadditional file named coreData.xcdatamodeld is also created. This is the file where the entity descriptions for our data model are going to be stored.

Creating the Entity DescriptionThe entity description defines the model for our data, much in the way a schema defines the model of a database table. To create the entity for the Core Dataapplication, select the coreData.xcdatamodeld file to load the entity editor:

To create a new entity, click on the Add Entity button located in the bottom panel. In the text field that appears beneath the Entities heading name the entityContacts. With the entity created, the next step is to add some attributes that represent the data that is to be stored. To do so, click on the Add Attribute button.

In the Attribute pane, name the attribute name and set the Type to String. Repeat these steps to add two other String attributes named address and phonerespectively:

Page 3: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

3/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

The entity is now defined and it is time to start writing code.

Adding a View ControllerIn order to automatically add Core Data support to our application we had to choose the Window-based Application project template option when we startedXcode. As such, we now need to create our own view controller.

Within the Xcode project navigator panel, Ctrl-click on the coreData folder entry. From the popup menu, select New File... In the new file panel, select the iOSCocoa Touch Class category followed by the UIViewController subclass icon and click Next. On the following options screen, select the With XIB for userinterface check box and make sure the Targeted for iPad option is off. Click Next and name the class coreDataViewController before clicking on the Save button.

Now that we have added the view controller class to the application we need to modify our app delegate to make this the root view controller. In the Xcodeproject navigator, select the coreDataAppDelegate.h file and modify it to add references to our new view controller:

#import <UIKit/UIKit.h>

@class coreDataViewController;

@interface coreDataAppDelegate : NSObject <UIApplicationDelegate> { coreDataViewController *viewController;}@property (nonatomic, retain) IBOutlet coreDataViewController *viewController;@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (void)saveContext;- (NSURL *)applicationDocumentsDirectory;@end

With an instance of the view controller declared in the interface file we now need to modify the applicationDidFinishLaunchingWithOptions method located in thecoreDataAppDelegate.m implementation file to add the view controller to our window. Note also that we have to import coreDataViewController.h into this fileand synthesize accessors for the viewController object:

#import "coreDataAppDelegate.h"#import "coreDataViewController.h"

@implementation coreDataAppDelegate@synthesize viewController;@synthesize window=_window;@synthesize managedObjectContext=__managedObjectContext;@synthesize managedObjectModel=__managedObjectModel;@synthesize persistentStoreCoordinator=__persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ // Override point for customization after application launch. [self.window addSubview:viewController.view]; [self.window makeKeyAndVisible]; return YES;}

Connecting the ViewThe next step is to add the new view controller to the project, associate it with the view NIB file and connect it to the application delegate.

Begin by selecting the MainWindow.xib file from the project navigator. From the Object library panel (View -> Utilities -> Object Library), drag a ViewController object and drop it beneath the Window object in the center objects panel. Once released, the new view controller should appear beneath the existingobjects as illustrated in the following figure:

Page 4: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

4/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

With the new view controller selected, open the Identity Inspector panel (View -> Utilities -> Identity Inspector) and change the Class value tocoreDataViewController:

Display the Attributes Inspector (View -> Utilities -> Attributes Inspector) and assign coreDataViewController as the NIB file.

Finally, establish a connection between the application delegate and the view controller. This is achieved by Ctrl-clicking on the coreData App Delegate object,dragging the resulting blue line to Core Data View Controller item in the same panel and selecting viewController from the menu:

Page 5: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

5/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

With the CoreData App Delegate Controller item selected in the MainWindow.xib file and the Connections Inspector displayed (View -> Utilities -> ConnectionsInspector), the settings should appear as shown in the following figure:

Now that we have a view controller programmed into our application we need to extend that class to include some actions and outlets.

Adding Actions and Outlets to the View ControllerAs with previous instances of our Contacts application, our Core Data example will include a user interface that needs to accept and display name, address andphone information and to react to the selection of the save and find buttons. In addition, a status label will be used to provide the user with feedback. To declarethe outlets and actions associated with these user interface components, select the coreDataViewController.h file and modify the class declaration so that it readsas follows:

#import <UIKit/UIKit.h>

@interface coreDataViewController : UIViewController { UITextField *name; UITextField *address; UITextField *phone; UILabel *status;}@property (nonatomic, retain) IBOutlet UITextField *name;@property (nonatomic, retain) IBOutlet UITextField *address;@property (nonatomic, retain) IBOutlet UITextField *phone;@property (nonatomic, retain) IBOutlet UILabel *status;- (IBAction) saveData;- (IBAction) findContact;@end

Next, select the coreDataViewController.m implementation file, add an @synthesize directive for the outlets, import the coreDataAppDelegate.h file and addtemplate methods for the two declared actions:

#import "coreDataViewController.h"#import "coreDataAppDelegate.h"

@implementation coreDataViewController@synthesize name, address, phone, status;

- (void) saveData{

Page 6: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

6/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

{}- (void) findContact{}..@end

Designing the User InterfaceWith the actions and outlets defined, now is a good time to design the user interface and establish the connections so select the coreDataViewController.xib file tobegin the design work. The user interface and corresponding connections used in this tutorial are the same as those in previous data persistence chapters. Thecompleted view should, once again, appear as follows:

Before proceeding, stretch the status label (located above the two buttons) so that it covers most of the width of the view. Finally, edit the label and remove theword “Label” so that it is blank.

Next, connect the three text fields and status label to the name, address, phone and status outlets respectively by holding down the Ctrl key and clicking anddragging from File’s Owner icon to the corresponding component. From the resulting menu select the outlet corresponding to the selected view object.

The last step involves connecting the two buttons to the corresponding actions. First, display the Connections Inspector (View -> Utilities -> ConnectionsInspector) then select the Save button. Click inside the small circle next to the Touch Up Inside event in the Connections Inspector panel and drag the blue line tothe File’s Owner object. To establish the connection, select saveData from the resulting menu. Repeat these steps to connect the Find button to the findContactaction.

Saving Data to the Persistent Store using Core DataWhen the user touches the Save button the saveData method is called. It is within this method, therefore, that we must implement the code to obtain the managedobject context and create and store managed objects containing the data entered by the user. Select the coreDataViewController.m file, scroll down to the templatesaveData method and implement the code as follows:

- (void) saveData{ coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *newContact; newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context]; [newContact setValue:name.text forKey:@"name"]; [newContact setValue:address.text forKey:@"address"]; [newContact setValue:phone.text forKey:@"phone"]; name.text = @""; address.text = @""; phone.text = @""; NSError *error; [context save:&error]; status.text = @”Contact saved”;}

The above code identifies the application delegate instance and uses that object to identify the managed object context. This context is then used to create a new

managed object using the Contacts entity description. The setValue method of the managed object is then called to set the name, address and phone attribute

Page 7: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

7/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

iPhone iOS 5Development

Essentials eBook$12.99

eBookFrenzy.com

managed object using the Contacts entity description. The setValue method of the managed object is then called to set the name, address and phone attributevalues of the managed object (which in turn are read from the text field user interface components). Finally the context is instructed to save the changes to thepersistent store with a call to the context’s save method.

Retrieving Data from the Persistent Store using Core DataIn order to allow the user to search for a contact it is now necessary to implement the findContact action method. As with the save method, this method will needto identify the application delegate and managed object context. It will then need to obtain the entity description for the Contacts entity and then create a predicateto ensure that only objects with the name specified by the user are retrieved from the store. Matching objects are placed in an array from which the attributes forthe first match are retrieved using the valueForKey method and displayed to the user. A full count of the matches is displayed in the status field. The code toperform these tasks is as follows:

- (void) findContact{ coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDesc]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", name.text]; [request setPredicate:pred]; NSManagedObject *matches = nil; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if ([objects count] == 0) { status.text = @"No matches"; } else { matches = [objects objectAtIndex:0]; address.text = [matches valueForKey:@"address"]; phone.text = [matches valueForKey:@"phone"]; status.text = [NSString stringWithFormat: @"%d matches found", [objects count]]; } [request release];}

Releasing MemoryPrior to compiling and running the example Core Data iPhone iOS application, it is important that we add code to free up any resources that were allocated duringexecution of the application. To do so, edit the coreDataViewController.m file and modify the viewDidUnload and dealloc methods as follows:

- (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; self.name = nil; self.address = nil; self.phone = nil; self.status = nil;}- (void)dealloc { [name release]; [address release]; [phone release]; [status release]; [super dealloc];}

Building and Running the Example ApplicationThe final step is to build and run the application. Click on the Run button located in the toolbar of the main Xcode project window. If errors are reported check thesyntax of the code you have written, using the error message provided by Xcode as guidance. Once the application compiles it will launch and load into the iOSSimulator. Enter some test contacts (some with the same name). Having entered some test data, enter the name of the contact for which you created duplicaterecords and click the Find button. The address and phone number of the first matching record should appear together with an indication in the status field of thetotal number of matching objects that were retrieved:

Page 8: An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

11/18/11 An iOS 4 iPhone Core Data Tutorial (Xcode 4) - Techotopia

8/8www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29

eBookFrenzy.com

Purchase and download the fully updated iOS 5 Edition of this book in Print ($27.99) or eBook ($12.99) format.iPhone iOS 5 Development Essentials Print and eBook (ePub/PDF) editions contain 56 chapters.

Previous Table of Contents NextWorking with iOS 4 iPhoneDatabases using Core Data(Xcode 4)

An Overview of iOS 4 iPhoneMultitouch, Taps and Gestures

(Xcode 4)Retrieved from "http://www.techotopia.com/index.php/An_iOS_4_iPhone_Core_Data_Tutorial_%28Xcode_4%29"

This page was last modified 18:10, 31 March 2011.Copyright 2011 Techotopia.com. All Rights Reserved.