Tutorial details

Store and Find an Employee using Core Data | App Code for Sale | Preview

Store and Find an Employee using Core Data | iOS Tutorial

This tutorial is based on the component Storing Employee information using Core Data
Download

Overview PAGE TOP

Core Data is a powerful framework on the iOS SDK that allows programmers to store and manage data in an object-oriented way. Traditionally, programmers had to store their data on disk using the archiving capabilities of Objective-C or write their data to files and manage them manually. With the introduction of Core Data, programmers can simply interact with its object-oriented interface to manage their data efficiently. Core Data is available in iOS beginning version 3.0

Core Data also provides the following features:

a. Change tracking and undo support.

b. Core Data maintains consistency of relationships among objects.

c. Validation of object property values.

d. Grouping, filtering, and organizing data in memory and in the user interface.

e. Sophisticated query compilation via predicates.

Following are the features of the tutorial :

(i). Store the Employee Information

(ii). Search for the Employee Information

(iii). Familiar with the Core Data Framework

(iv). Familiar with the Creation of the Entities and adding attributes within the Core Data

(v). Familiar with ARC (Automatic Reference Counting)

Project Set-Up: PAGE TOP

Create new project in XCode that will use Empty application template and name it as ‘CoreData’. Ensure that you have the Use Core Data and Automatic Reference Counting option checked as shown below.

153.png

Create a new file, Right Click on the Project Select 'New File' and name the file as CoreDataViewController (extending the UIViewController Class) with Xib file as shown :

239.png

Create a new file, Right Click on the Project Select 'New File' and name the file as CoreDataViewController (extending the UIViewController Class) with Xib file as shown :

337.png

Programming: PAGE TOP

In AppDelegate.m file, import the CoreDataViewController.h and make the rootViewController as CoreDataViewController.

#import “CoreDataViewController.h ”

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    CoreDataViewController *coreDataViewController = [[CoreDataViewController alloc] init];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:coreDataViewController];
    self.window.rootViewController = navigationController;

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Add Two more files i.e, 'AddEmployeeViewController' and 'FindEmployeeViewController' the same way you added above. Go to the 'CoreData.xcdatamodeld' file add an entity by tapping '+' below and name it as 'Employee'. Now add the attributes to the Employee Entity as 'employeeID', 'employeeName' and 'phoneNo' with type as string as shown below:

461.png

Go to the CoreDataViewController.xib, change the background color as Grouped table view background/white color, add two buttons and name it as 'Add a Employee' and 'Find a employee' and link the touch up inside methods addEmployee and findEmployee.

555.png

652.png

After linking the CoreDataViewcontroller.h looks like:

-(IBAction)addEmployee:(id)sender;
-(IBAction)findEmployee:(id)sender;

In CoreDataViewcontroller.m add the following:

#import "AddEmployeeViewController.h"
#import "FindEmployeeViewController.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Employee";
}
- (IBAction)addEmployee:(id)sender {
    AddEmployeeViewController *addEmployeeViewController = [[AddEmployeeViewController alloc] init];
    [self.navigationController pushViewController:addEmployeeViewController animated:YES];
}

- (IBAction)findEmployee:(id)sender {
    FindEmployeeViewController *findEmployeeViewController = [[FindEmployeeViewController alloc] init];
    [self.navigationController pushViewController:findEmployeeViewController animated:YES];
}

The above code, navigates from Core data home view controller to the add or findEmployeeViewController.

In AddEmployeeViewController.xib, change the background color as Grouped table view background/white color, add three text fields and name it as employeeId, employeeName and employeePhone and link the same to the .h file. In employeeId attributes Inspector change the clear button mode to the 'Appears while editing', do the same for the employeeName and employeePhone text fields. Add the place holder string as an employeeId, employeeName and employeePhone. In employeeId and employeePhone attributes Inspector change the keyboard type to 'Phone Pad'. Add the status label below the text fields, change the title to empty string and link the same to .h file.

8.png

9.png

The AddEmployeeViewController.h looks like:

#import "AppDelegate.h"

@interface AddEmployeeViewController : UIViewController<UITextFieldDelegate>
{

}
@property (nonatomic, strong) IBOutlet UILabel *status;
@property (nonatomic, strong) IBOutlet UITextField *employeeId;
@property (nonatomic, strong) IBOutlet UITextField *employeeName;
@property (nonatomic, strong) IBOutlet UITextField *employeePhone;

-(IBAction)addAEmployee:(id)sender;
-(void) showAlert :(NSString*)title Message:(NSString*)msg;
@end

In AddEmployeeViewController.m add the following :

@synthesize status, employeeId, employeeName, employeePhone;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Add Employee";

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(addAEmployee:)];
    self.navigationItem.rightBarButtonItem = addButton;
}

-(IBAction)addAEmployee:(id)sender
{
    if([self.employeeId.text length] ==0)
    { 
        [self.employeeId resignFirstResponder];
        [self showAlert:@"" Message:@"Please enter Employee Id"];
    }
    else if([self.employeeName.text length] ==0)
    {
        [self.employeeName resignFirstResponder];
        [self showAlert:@"" Message:@"Please enter Employee name"];
    }
    else if([self.employeePhone.text length] ==0)
    {
        [self.employeePhone resignFirstResponder];
        [self showAlert:@"" Message:@"Please enter Employee Phone Number"];
    }
    else{
        [self.employeeId resignFirstResponder];
        [self.employeeName resignFirstResponder];
         [self.employeePhone resignFirstResponder];
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

        NSManagedObjectContext *context = [appDelegate managedObjectContext];
        NSManagedObject *newContact;
        newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:context];
        [newContact setValue:self.employeeId.text forKey:@"employeeID"];
        [newContact setValue:self.employeeName.text forKey:@"employeeName"];
        [newContact setValue:self.employeePhone.text forKey:@"phoneNo"];
        self.employeeId.text = @"";
        self.employeeName.text = @"";
        self.employeePhone.text = @"";
        NSError *error;
        [context save:&error];
        status.text = @"Contact saved";
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void) showAlert :(NSString*)title Message:(NSString*)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
}

When the user touches the Save button the addAEmployee method is called. It is within this method, therefore, that we must implement the code to obtain the managed object context and create and store managed objects containing the data entered by the user. 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 Employee entity description. The setValue method of the managed object is then called to set the employeeId, name and phone attribute values 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 the persistent store with a call to the context’s save method.

In FindEmployeeViewController.xib, add the Label at the top and set the title as 'Enter the Employee Id:', add a text field below the Label and name it as employeeId and set the place holder as same. Select the textfield and change the attributes clear button mode as 'Clear while editing' and return key as 'Search'. Add two Labels below the textfield and name it as the textLabel and Status and link the same with the .h file as shown below:

10.png

11.png

The FindEmployeeViewController.h looks like:

#import "AppDelegate.h"
@interface FindEmployeeViewController : UIViewController
{

}
@property (nonatomic, strong) IBOutlet UITextField *employeeId;
@property (nonatomic, strong) IBOutlet UILabel *textLabel;
@property (nonatomic, strong) IBOutlet UILabel *status;
@end

In FindEmployeeViewController.m add the following:

@synthesize employeeId, textLabel, status;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Find Employee";
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([self.employeeId.text length]==0)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Please enter Employee Id" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
    else{
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = [appDelegate managedObjectContext];
        NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Employee" 
                                                      inManagedObjectContext:context];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entityDesc];
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"(employeeID = %@)", 
                             self.employeeId.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];
            self.textLabel.text = [NSString stringWithFormat:@"The Employee Name = %@ and Phone No = %@", [matches valueForKey:@"employeeName"], [matches valueForKey:@"phoneNo"]];
            self.status.text = [NSString stringWithFormat:
                                @"%d matches found", [objects count]];
        }

    }
    [textField resignFirstResponder];
    return YES;
}

In order to allow the user to search for a employee it is now necessary to implement the textFieldShouldReturn action method. As with the save method, this method will need to identify the application delegate and managed object context. It will then need to obtain the entity description for the Employee entity and then create a predicate to 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 for the 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.

Building and Running the Application: PAGE TOP

The final step is to build and run the application. Click on the Build and Run button located in the toolbar of the main Xcode project window. Assuming an absence of compilation errors, the application should load into the iOS Simulator environment.

1273.png

1387.png

1473.png

1510.png

1734.png

18.png

Project Set-Up: PAGE TOP

Create new project in XCode that will use Empty application template and name it as ‘CoreData’. Ensure that you have the Use Core Data and Automatic Reference Counting option checked as shown below.

153.png

Create a new file, Right Click on the Project Select 'New File' and name the file as CoreDataViewController (extending the UIViewController Class) with Xib file as shown :

239.png

Create a new file, Right Click on the Project Select 'New File' and name the file as CoreDataViewController (extending the UIViewController Class) with Xib file as shown :

337.png

Programming: PAGE TOP

In AppDelegate.m file, import the CoreDataViewController.h and make the rootViewController as CoreDataViewController.

#import “CoreDataViewController.h ”

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    CoreDataViewController *coreDataViewController = [[CoreDataViewController alloc] init];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:coreDataViewController];
    self.window.rootViewController = navigationController;

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Add Two more files i.e, 'AddEmployeeViewController' and 'FindEmployeeViewController' the same way you added above. Go to the 'CoreData.xcdatamodeld' file add an entity by tapping '+' below and name it as 'Employee'. Now add the attributes to the Employee Entity as 'employeeID', 'employeeName' and 'phoneNo' with type as string as shown below:

461.png

Go to the CoreDataViewController.xib, change the background color as Grouped table view background/white color, add two buttons and name it as 'Add a Employee' and 'Find a employee' and link the touch up inside methods addEmployee and findEmployee.

555.png

652.png

After linking the CoreDataViewcontroller.h looks like:

-(IBAction)addEmployee:(id)sender;
-(IBAction)findEmployee:(id)sender;

In CoreDataViewcontroller.m add the following:

#import "AddEmployeeViewController.h"
#import "FindEmployeeViewController.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Employee";
}
- (IBAction)addEmployee:(id)sender {
    AddEmployeeViewController *addEmployeeViewController = [[AddEmployeeViewController alloc] init];
    [self.navigationController pushViewController:addEmployeeViewController animated:YES];
}

- (IBAction)findEmployee:(id)sender {
    FindEmployeeViewController *findEmployeeViewController = [[FindEmployeeViewController alloc] init];
    [self.navigationController pushViewController:findEmployeeViewController animated:YES];
}

The above code, navigates from Core data home view controller to the add or findEmployeeViewController.

In AddEmployeeViewController.xib, change the background color as Grouped table view background/white color, add three text fields and name it as employeeId, employeeName and employeePhone and link the same to the .h file. In employeeId attributes Inspector change the clear button mode to the 'Appears while editing', do the same for the employeeName and employeePhone text fields. Add the place holder string as an employeeId, employeeName and employeePhone. In employeeId and employeePhone attributes Inspector change the keyboard type to 'Phone Pad'. Add the status label below the text fields, change the title to empty string and link the same to .h file.

8.png

9.png

The AddEmployeeViewController.h looks like:

#import "AppDelegate.h"

@interface AddEmployeeViewController : UIViewController<UITextFieldDelegate>
{

}
@property (nonatomic, strong) IBOutlet UILabel *status;
@property (nonatomic, strong) IBOutlet UITextField *employeeId;
@property (nonatomic, strong) IBOutlet UITextField *employeeName;
@property (nonatomic, strong) IBOutlet UITextField *employeePhone;

-(IBAction)addAEmployee:(id)sender;
-(void) showAlert :(NSString*)title Message:(NSString*)msg;
@end

In AddEmployeeViewController.m add the following :

@synthesize status, employeeId, employeeName, employeePhone;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Add Employee";

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(addAEmployee:)];
    self.navigationItem.rightBarButtonItem = addButton;
}

-(IBAction)addAEmployee:(id)sender
{
    if([self.employeeId.text length] ==0)
    { 
        [self.employeeId resignFirstResponder];
        [self showAlert:@"" Message:@"Please enter Employee Id"];
    }
    else if([self.employeeName.text length] ==0)
    {
        [self.employeeName resignFirstResponder];
        [self showAlert:@"" Message:@"Please enter Employee name"];
    }
    else if([self.employeePhone.text length] ==0)
    {
        [self.employeePhone resignFirstResponder];
        [self showAlert:@"" Message:@"Please enter Employee Phone Number"];
    }
    else{
        [self.employeeId resignFirstResponder];
        [self.employeeName resignFirstResponder];
         [self.employeePhone resignFirstResponder];
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

        NSManagedObjectContext *context = [appDelegate managedObjectContext];
        NSManagedObject *newContact;
        newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:context];
        [newContact setValue:self.employeeId.text forKey:@"employeeID"];
        [newContact setValue:self.employeeName.text forKey:@"employeeName"];
        [newContact setValue:self.employeePhone.text forKey:@"phoneNo"];
        self.employeeId.text = @"";
        self.employeeName.text = @"";
        self.employeePhone.text = @"";
        NSError *error;
        [context save:&error];
        status.text = @"Contact saved";
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void) showAlert :(NSString*)title Message:(NSString*)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
}

When the user touches the Save button the addAEmployee method is called. It is within this method, therefore, that we must implement the code to obtain the managed object context and create and store managed objects containing the data entered by the user. 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 Employee entity description. The setValue method of the managed object is then called to set the employeeId, name and phone attribute values 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 the persistent store with a call to the context’s save method.

In FindEmployeeViewController.xib, add the Label at the top and set the title as 'Enter the Employee Id:', add a text field below the Label and name it as employeeId and set the place holder as same. Select the textfield and change the attributes clear button mode as 'Clear while editing' and return key as 'Search'. Add two Labels below the textfield and name it as the textLabel and Status and link the same with the .h file as shown below:

10.png

11.png

The FindEmployeeViewController.h looks like:

#import "AppDelegate.h"
@interface FindEmployeeViewController : UIViewController
{

}
@property (nonatomic, strong) IBOutlet UITextField *employeeId;
@property (nonatomic, strong) IBOutlet UILabel *textLabel;
@property (nonatomic, strong) IBOutlet UILabel *status;
@end

In FindEmployeeViewController.m add the following:

@synthesize employeeId, textLabel, status;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Find Employee";
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([self.employeeId.text length]==0)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Please enter Employee Id" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
    else{
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = [appDelegate managedObjectContext];
        NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Employee" 
                                                      inManagedObjectContext:context];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entityDesc];
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"(employeeID = %@)", 
                             self.employeeId.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];
            self.textLabel.text = [NSString stringWithFormat:@"The Employee Name = %@ and Phone No = %@", [matches valueForKey:@"employeeName"], [matches valueForKey:@"phoneNo"]];
            self.status.text = [NSString stringWithFormat:
                                @"%d matches found", [objects count]];
        }

    }
    [textField resignFirstResponder];
    return YES;
}

In order to allow the user to search for a employee it is now necessary to implement the textFieldShouldReturn action method. As with the save method, this method will need to identify the application delegate and managed object context. It will then need to obtain the entity description for the Employee entity and then create a predicate to 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 for the 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.

Building and Running the Application: PAGE TOP

The final step is to build and run the application. Click on the Build and Run button located in the toolbar of the main Xcode project window. Assuming an absence of compilation errors, the application should load into the iOS Simulator environment.

1273.png

1387.png

1473.png

1510.png

1734.png

18.png

2 Comments Leave a comment

Please login in order to leave a comment.

Newest first
  • malboro 2012-09-04 04:07:02 Thread #17

    congratulations, I bought this, I have a problem. How can I get the view of other matches found and not only the number but also the text. in the text view always displays only one result.

  • ravinderkumar 2012-08-16 10:51:44 Thread #16

    good

!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.