Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Core Data in iOS Part 1?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 458
    Comment on it

    Core Data framework is used to store data in the form of entities and maintained by Apple in a very well defined manner. Here is an example usage of Core Data to insert,delete,update and fetch data from entities with in the same. To use Core Data with in the project while creating the project select Core Data option as given in the screenshot.

     

     

     

     

    When Core Data is selected while creating the project it will automatically create a Core Data file with extension .xcdatamodelId which will be shown within the project in this way as given in screenshot. Now create entity to store data by using Add entity option given at the bottom after clicking on Core Data file. Enter attributes within entity to store data after insertion. Now below screenshot includes how to create entity after click on Add Entity. We will create subclass of entity which will automatically create properties which we can access further.

     

     

     

     

     

     


    In below way we will get the subclasses of entity created with in the Core Data file:-

     

     

     

    After creating the entity named as Employee  now its time to design User Interface to take input from user which will save in Employee entity. First controller will show the list of employee added by user and within the same controller at top we will provide a button to add new employee. Followed by add employee form which includes 3 fields in it name,designation and salary. Controllers are connected with the help of present modally storyboard segue which will further help in animation.

     

     

     

     

     

     

     

    Subclasses which are created will contain some properties which are accessible for further work. When you will open these subclasses some code will be given in the following way :-

     

     

    Employee.h
    
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
    
    @class Company;
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Employee : NSManagedObject
    
    // Insert code here to declare functionality of your managed object subclass
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Employee+CoreDataProperties.h"
    
    
    Employee.m
    
    
    #import "Employee.h"
    #import "Company.h"
    
    @implementation Employee
    
    // Insert code here to add functionality to your managed object subclass
    
    @end
    
    
    Employee+CoreDataProperties.h
    
    
    #import "Employee.h"
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Employee (CoreDataProperties)
    
    @property (nullable, nonatomic, retain) NSString *employee_Designation;
    @property (nullable, nonatomic, retain) NSString *employee_Name;
    @property (nullable, nonatomic, retain) NSString *employee_Salary;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    
    Employee+CoreDataProperties.m
    
    
    #import "Employee+CoreDataProperties.h"
    
    @implementation Employee (CoreDataProperties)
    
    @dynamic employee_Designation;
    @dynamic employee_Name;
    @dynamic employee_Salary;
    
    @end

     


    File which is given below is used to declare and define constant so that we don’t have to write strings again we can simply use constant strings by importing the below file:-
     

     

    StringDeclaration.h
    
    
    #import <Foundation/Foundation.h>
    
    @interface StringDeclaration : NSObject
    extern NSString *const cellIdentifier,*const name,*const designation,*const salary;
    @end
    
    StringDeclaration.m
    
    
    #import "StringDeclaration.h"
    
    @implementation StringDeclaration
    NSString * const cellIdentifier=@"cell",*const name=@"employee_Name",*const designation=@"employee_Designation",*const salary=@"employee_Salary";
    @end
    
    

     

     

    First controller includes tableview which will display the list of added employees and we will set the identifier for cell also. Class for table cell is also created but no outlet is created as we are taking cell style as right align so automatically two labels will come one for title and another for detail so according to the need we can choose the cell style. Code to fetch the data from Core Data is given below:-

     

     

    DataOfEmployeeTableViewCell.h
    
    #import <UIKit/UIKit.h>
    
    @interface DataOfEmployeeTableViewCell : UITableViewCell
    
    @end
    
    DataOfEmployeeTableViewCell.m
    
    #import "DataOfEmployeeTableViewCell.h"
    
    @implementation DataOfEmployeeTableViewCell
    
    - (void)awakeFromNib {
        // Initialization code
    }
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
        [super setSelected:selected animated:animated];
    
        // Configure the view for the selected state
    }
    
    @end

     

    Below is the code for employee list so name of the file is taken as EmployeeListViewController so that it become easy to understand why the file used. Always remember the naming conventions before providing the name to the classes , outlets ,strings etc. so that it become easy to understand the code.  

     

    
    
    EmployeeListViewController.h
    
    
    #import <UIKit/UIKit.h>
    
    @interface EmployeeViewController : UIViewController
    - (IBAction)btnAddEmployee:(id)sender;
    - (IBAction)addCompany:(id)sender;
    @property (weak, nonatomic) IBOutlet UITableView *tblView; //outlet of table view
    
    @end
    
    
    EmployeeListViewController.m
    
    #import "EmployeeViewController.h"
    #import <CoreData/CoreData.h>
    #import "AddEmployeeDetailViewController.h"
    #import "StringDeclaration.h"
    
    @interface EmployeeViewController ()
    @property (strong) NSMutableArray *employeeArray;
    @end
    
    @implementation EmployeeViewController
    
    - (NSManagedObjectContext *)managedObjectContext
    {
        NSManagedObjectContext *context = nil;
        id delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate performSelector:@selector(managedObjectContext)]) {
            context = [delegate managedObjectContext];
        }
        return context;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        // Do any additional setup after loading the view.
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        
        // Dispose of any resources that can be recreated.
    }
    
    - (void)viewDidAppear:(BOOL)animated
    {
       
        [super viewDidAppear:animated];
        [self data];
        [self.tblView reloadData];
        // Fetch the devices from persistent data store
     
    }
    -(void)data
    {
        NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Employee"];
        self.employeeArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
       
    }
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        // Return the number of rows in the section.
        return self.employeeArray.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        // Configure the cell...
        NSManagedObject *employee = [self.employeeArray objectAtIndex:indexPath.row];
        [cell.textLabel setText:[NSString stringWithFormat:@"%@ %@", [employee valueForKey:name], [employee valueForKey:designation]];
        [cell.detailTextLabel setText:[employee valueForKey:salary]];
        return cell;
    }
    
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Return NO if you do not want the specified item to be editable.
        return YES;
    }
    
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSManagedObjectContext *context = [self managedObjectContext];
        
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            // Delete object from database
            [context deleteObject:[self.employeeArray objectAtIndex:indexPath.row]];
            
            NSError *error = nil;
            if (![context save:&error]) {
                NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
                return;
            }
            
            // Remove device from table view
            [self.employeeArray removeObjectAtIndex:indexPath.row];
            [self.tblView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
    
    
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue identifier] isEqualToString:@"Update"]) {
            NSManagedObject *selectedDevice = [self.employeeArray objectAtIndex:[[self.tblView indexPathForSelectedRow] row]];
            AddEmployeeDetailViewController *destViewController = segue.destinationViewController;
            destViewController.employeeObject = selectedDevice;
            
        }
    }
    
    - (IBAction)btnAddEmployee:(id)sender {
    
        UIStoryboard*  sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        AddEmployeeDetailViewController* vc1 = [sb instantiateViewControllerWithIdentifier:NSStringFromClass([AddEmployeeDetailViewController class])];
        [vc1 setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
        [self presentViewController:vc1 animated:YES completion:nil];
    
    }
    
    
    

     

    Below is the code for adding a new employee which is done in file of UIViewController type and name of file is AddEmployeeDetailViewController

    
    
    AddEmployeeDetailViewController.h
    
    #import <UIKit/UIKit.h>
    #import <CoreData/CoreData.h>
    #import "Employee.h"
    
    @interface AddEmployeeDetailViewController : UIViewController
    
    @property (weak, nonatomic) IBOutlet UITextField *txtEmployeeName;//outlet of textfield used to take input from user
    @property (weak, nonatomic) IBOutlet UITextField *txtEmployeeDesignation;
    @property (weak, nonatomic) IBOutlet UITextField *txtEmployeeSalary;
    - (IBAction)btnSave:(id)sender;// button outlet to save data in Core Data
    - (IBAction)btnCancel:(id)sender;
    @property (strong) NSManagedObject *employeeObject;
    @end
    
    
    AddEmployeeDetailViewController.m
    
    #import "AddEmployeeDetailViewController.h"
    #import "StringDeclaration.h"
    
    @interface AddEmployeeDetailViewController ()
    
    @end
    
    @implementation AddEmployeeDetailViewController
    
    - (NSManagedObjectContext *)managedObjectContext {
        NSManagedObjectContext *context = nil;
        id delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate performSelector:@selector(managedObjectContext)]) {
            context = [delegate managedObjectContext];
        }
        return context;
    }
    
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //if data was present in the table view than on click data will display in textfeild.
        if (self.employeeObject) {
            [self.txtEmployeeName setText:[self.employeeObject valueForKey:name]];
            [self.txtEmployeeDesignation setText:[self.employeeObject valueForKey:designation]];
            [self.txtEmployeeSalary setText:[self.employeeObject valueForKey:salary]];
        }
        
    
    }
    
    
    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    
    }
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (IBAction)btnSave:(id)sender {
    
        
        NSManagedObjectContext *context = [self managedObjectContext];
        
        if (self.employeeObject) {
            // Update existing employee record
    
            [self.employeeObject setValue:self.txtEmployeeName.text forKey:name];
            [self.employeeObject setValue:self.txtEmployeeDesignation.text forKey:designation];
            [self.employeeObject setValue:self.txtEmployeeSalary.text forKey:salary];
    
            
        } else {
            // Create a new employee record
            Employee *newDevice = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Employee class]) inManagedObjectContext:context];
            newDevice.employee_Name=self.txtEmployeeName.text;
            newDevice.employee_Designation=self.txtEmployeeDesignation.text;
            newDevice.employee_Salary=self.txtEmployeeSalary.text;
            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
            
           
        }
         [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    - (IBAction)btnCancel:(id)sender {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    @end
    
    
    

     

    So after all this above coding you will be able to execute the program . If after one time execution you are doing any kind of change in entities so you have to again create the subclasses , delete the application from simulator and than execute the application .

    Output:-

    Before taking the screenshot of output I have changed the color of controllers so different colors you can provide to the background of controllers.First screen will be visible in this way :-

     

     

     

    On click of button Add Employee Below screen will be visible and you can add new user from here :-

     

     

     

    Delete can be done on scroll the cell of table view of first controller as given in below screenshot and we can easily delete the selected row data of the cell :-

     

     

     

    Update can be done by clicking on any cell of the table view of first controller which includes Employee List and take the user to another controller to save the new updated data . In below screenshot I have updated the salary from 2000000 to 3000000 .

     

     

     

    After saving the updated data that change  will be visible in table view also as given in screenshot below :-

     

     

     

     

    You can download the project from the given link . You need Xcode 7.2 to build the project .

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: