Core Data in iPhone

Introduction

In this article I will create a contact book. We will use three text fields, for name, address, phone entities and two buttons, a "save" button to save the contact details in the phone book and a "find" button to search contacts by name from outlet.

Here we add core data from cocoa touch and add it's functionality to the project.

Step 1

Open Xcode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now select Single View Application and click on Next.

Step 4

Now provide your Product Name and Company Identifier then click on Next.

Step 5

Select the location where you want to save your project and click on Create.

Step 6

The followng is the code:

AppDelegate.h

//

//coreDataAppDelegate.h

//CoreData

//

//Created by Sachin Bhardwaj on 15/01/13.

//Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

@class coreDataViewController;

@interface coreDataAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) coreDataViewController *viewController;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;

@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;

@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;

- (NSURL *)applicationDocumentsDirectory;

@end


AppDelegate.m

//

//coreDataAppDelegate.m

//CoreData

//

//Created by Sachin Bhardwaj on 15/01/13.

//Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "coreDataAppDelegate.h"

#import "coreDataViewController.h"

@implementation coreDataAppDelegate

@synthesize managedObjectContext;

@synthesize managedObjectModel;

@synthesize persistentStoreCoordinator;

- (void)dealloc

{

[_window release];

[_viewController release];

[super dealloc];

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

// Override point for customization after application launch.

self.viewController = [[[coreDataViewController alloc] initWithNibName:@"coreDataViewController" bundle:nil] autorelease];

self.window.rootViewController = self.viewController;

[self.window makeKeyAndVisible];

return YES;

}

- (void)applicationWillResignActive:(UIApplication *)application

{

// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

- (void)applicationDidEnterBackground:(UIApplication *)application

{

// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

- (void)applicationWillEnterForeground:(UIApplication *)application

{

// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication *)application

{

// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}

- (void)applicationWillTerminate:(UIApplication *)application

{

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

}

- (void)saveContext

{

NSError *error = nil;

NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

if (managedObjectContext != nil)

{

if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])

{

/*

Replace this implementation with code to handle the error appropriately.

abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

*/

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

abort();

}

}

}

#pragma mark - Core Data stack

/**

Returns the managed object context for the application.

If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.

*/

- (NSManagedObjectContext *)managedObjectContext

{

if (managedObjectContext != nil)

{

return managedObjectContext;

}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

if (coordinator != nil)

{

managedObjectContext = [[NSManagedObjectContext alloc] init];

[managedObjectContext setPersistentStoreCoordinator:coordinator];

}

return managedObjectContext;

}

/**

Returns the managed object model for the application.

If the model doesn't already exist, it is created from the application's model.

*/

- (NSManagedObjectModel *)managedObjectModel

{

if (managedObjectModel != nil)

{

return managedObjectModel;

}

managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

return managedObjectModel;

}

/**

Returns the persistent store coordinator for the application.

If the coordinator doesn't already exist, it is created and the application's store added to it.

*/

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

if (persistentStoreCoordinator != nil)

{

return persistentStoreCoordinator;

}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTabBarTutorial.sqlite"];

NSError *error = nil;

persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

{

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

abort();

}

return persistentStoreCoordinator;

}

- (NSURL *)applicationDocumentsDirectory

{

return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

@end


ViewController.h

//

//coreDataViewController.h

//CoreData

//

//Created by Sachin Bhardwaj on 15/01/13.

//Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface coreDataViewController : UIViewController

@property (strong, nonatomic) IBOutlet UITextField *name;

@property (strong, nonatomic) IBOutlet UITextField *address;

@property (strong, nonatomic) IBOutlet UITextField *phone;

@property (strong, nonatomic) IBOutlet UILabel *status;

- (IBAction) saveData;

- (IBAction) findContact;

@end


ViewController.m

//

//coreDataViewController.m

//CoreData

//

//Created by Sachin Bhardwaj on 15/01/13.

//Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "coreDataViewController.h"

#import "coreDataAppDelegate.h"

@interface coreDataViewController ()

@end

@implementation coreDataViewController

@synthesize name, address, phone, status;

- (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";

}

- (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]];

}

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

return self;

}

- (void)didReceiveMemoryWarning

{

// Releases the view if it doesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view from its nib.

}


- (void)viewDidUnload

{

[super 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;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

// Return YES for supported orientations

return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

@end

ViewController.Xib

Xib-file-in-iPhone.png

coreData.xcdatamodeled

core-data-in-iPhone.png

Step 7

Now select the iPhone platform to see the output in the Simulator.

Output:

Output1 in iPhone:

Output1-in-iPhone.png

Output2 in iPhone:

Output2-in-iPhone.png

To save the data here we click on the save button.

Output3 in iPhone:

Output3-in-iPhone.png

Massage displayed in the label.

Output4 in iPhone:

Output4-in-iPhone.png

Here we add new contact information. 

Output5 in iPhone:

Output5-in-iPhone.png

To find information of a person whose record was perviously saved, we write the name of the person and click on the find button. 

Output6 in iPhone:

Output6-in-iPhone.png

The message is displayed in the label.


Similar Articles