×


Core Data


What is Core Data ?

Lets clear one thing, Core Data is not a database. Core data is just a framework that lets developers save or retrieve data easily without even knowing any SQL. This data is stored inside SQLite database and that's why SQLite is default persistent store of Core data. Core data is just a high-level framework which is used to persist data without even knowing any high-level SQL queries. Let's dive deep into this...

Core Data Stack

Core data stack is divided into following components,

1. Managed Object Model

2. Persistent Store Coordinator

3. Managed Object Context

1. Managed Object Model

Consider managed object model as a schema in database. In Sql we create database , inside that database we create tables. Similarly, managed object model is schema in core data. It is denoted with extension .xcdatamodeld

2. Managed Object Context

In the given list of Core data stack you will only interact with this one. Object Context is used to manage objects created and returned using Core Data. Whenever you need to save and fetch objects in core data, Managed object context is the first component you have to talk with.


3. Persistent Store Coordinator

Persistent store coordinator is used to coordinate with object context and main data store i.e database. You will never work with this one in Core data programming.

Create a new project

Open Xcode Goto File > New >Project >Single View Application > Enter Project Name (eg :- CoreDataDemo) > Done.



In CoreDataDemo.xcdatamodeld,


In .xcdatmodel you can create entity with Add Entity button as you see at bottom of this image . In this example, we are going to create Student entity which contains name & course attributes with datatypes string.

In Appdelegate.h

AppDelegate is the file which is called first when your App Starts . You have to specify which viewController you want to begin with. In this case ViewController is set as rootViewController.

self.window.rootViewController = navController;

In this way you can set Root View Controller . In our case we want ViewController file to be the first one to start.

UINavigationController is used in many iOS apps which helps in controlling the navigation.

As this project is using Core Data, you have to specify few more things in Appdelegate.

1. Managed Object Model

Add this code in AppDelegate.m file,

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel !=   nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL  =   [[NSBundle mainBundle] URLForResource:@"CoreDataDemo" withExtension:@"momd"];
    _managedObjectModel  =   [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

2. Persistent Store Coordinator

Add this code in AppDelegate.m file, Just make sure you specify your project name URLByAppendingPathComponent with .sqlite extension.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator !=   nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator  =   [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
    NSURL *storeURL  =   [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataDemo.sqlite"];
   
    NSError *error  =   nil;
    NSString *failureReason  =   @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil
                                                             URL:storeURL options:nil error:&error])
    {
        // Report any error we got.
        NSMutableDictionary *dict  =   [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey]  =   @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey]  =   failureReason;
        dict[NSUnderlyingErrorKey]  =   error;
        error  =   [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this 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.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return _persistentStoreCoordinator;
}

3. Managed Object Context

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support
- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = 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.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

Final AppDelegate.h file looks like this

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (strong, nonatomic) UIWindow *window;

- (void)saveContext;
@end

In AppDelegate.m

import "AppDelegate.h"
#import "ViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
    // Override point for customisation after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    // App Navigation Appearance
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    [[UINavigationBar appearance] setTranslucent:NO];
    if( [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 )
    {
        [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.0/255.0 green:120.0/255.0 blue:176.0/255.0 alpha:1.0]];
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init]
                                          forBarPosition:UIBarPositionAny
                                              barMetrics:UIBarMetricsDefault];
        
        [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
        
    }
    
    ViewController *abcController = [[ViewController alloc]init];
    
    UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:abcController];
    self.window.rootViewController = navController;
    [self.window makeKeyAndVisible];
    return YES;
}

#pragma mark - Core Data stack

@synthesize managedObjectContext  =   _managedObjectContext;
@synthesize managedObjectModel  =   _managedObjectModel;
@synthesize persistentStoreCoordinator  =   _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "Abc.healthcoco" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel !=   nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL  =   [[NSBundle mainBundle] URLForResource:@"CoreDataDemo" withExtension:@"momd"];
    _managedObjectModel  =   [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator !=   nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator  =   [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
    NSURL *storeURL  =   [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataDemo.sqlite"];
    NSDictionary *options = @{
                              NSMigratePersistentStoresAutomaticallyOption : @YES,
                              NSInferMappingModelAutomaticallyOption : @YES
                              };
    NSError *error  =   nil;
    NSString *failureReason  =   @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil
                                                             URL:storeURL options:options error:&error])
    {
        // Report any error we got.
        NSMutableDictionary *dict  =   [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey]  =   @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey]  =   failureReason;
        dict[NSUnderlyingErrorKey]  =   error;
        error  =   [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this 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.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = 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.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


@end

Saving Student Information in core data


Create a new view controller named CoreDataDetailsViewController which will be used for saving student information inside core data. Goto File > New > File > Cocoa Touch Class > Next > Enter File name > CoreDataDetailsViewController > Next > Create.



- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

-(void)saveButtonClicked
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
    // Create a new managed object
    NSManagedObject *studentInfo = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
    [studentInfo setValue:textFieldName.text forKey:@"name"];
    [studentInfo setValue:textFieldCourse.text forKey:@"course"];
    
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

Insertion inside core data is very simple and easy task. With insertNewObjectForEntityForName method you can insert studentInfo inside core data to specified entity Student. As you notice inside saveButtonClicked method, you can setValue inside NSmanagedObject just like you setValue in NSDictionary.

Final CoreDataDetailsViewController.m file looks like this,

This file is used for inserting data inside core data entity.

#import "CoreDataDetailsViewController.h"
#import <CoreData/CoreData.h>
#define PADDING   12
@interface CoreDataDetailsViewController ()
{
    UITextField *textFieldName;
    UITextField *textFieldCourse;
}
@end

@implementation CoreDataDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveButtonClicked)];
    
    [self initialiseCoreDataDetailView];
}

-(void)initialiseCoreDataDetailView
{
    UILabel *labelName = [[UILabel alloc]initWithFrame:CGRectMake(PADDING, PADDING*3, 120, 24)];
    [self.view addSubview:labelName];
    labelName.textColor = [UIColor blackColor];
    labelName.font = [UIFont fontWithName:@"Helvetica" size:16.0];
    labelName.text = @"Name";
    
    textFieldName = [[UITextField alloc]initWithFrame:CGRectMake(PADDING + CGRectGetMaxX(labelName.frame), PADDING*3, 240, 36)];
    [self.view addSubview:textFieldName];
    textFieldName.placeholder = @"Name";
    textFieldName.layer.borderWidth = 1.0;
    textFieldName.textAlignment = NSTextAlignmentCenter;
    
    UILabel *labelCourse = [[UILabel alloc]initWithFrame:CGRectMake(PADDING, CGRectGetMaxY(labelName.frame) + PADDING*3, 120, 24)];
    [self.view addSubview:labelCourse];
    labelCourse.textColor = [UIColor blackColor];
    labelCourse.font = [UIFont fontWithName:@"Helvetica" size:16.0];
    labelCourse.text = @"Course";
    
    textFieldCourse = [[UITextField alloc]initWithFrame:CGRectMake(PADDING + CGRectGetMaxX(labelCourse.frame), CGRectGetMaxY(labelName.frame) + PADDING*3, 240, 36)];
    [self.view addSubview:textFieldCourse];
    textFieldCourse.placeholder = @"Course";
    textFieldCourse.layer.borderWidth = 1.0;
    textFieldCourse.textAlignment = NSTextAlignmentCenter;
}


- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}
#pragma mark - Actions
-(void)saveButtonClicked
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
    // Create a new managed object
    NSManagedObject *studentInfo = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
    [studentInfo setValue:textFieldName.text forKey:@"name"];
    [studentInfo setValue:textFieldCourse.text forKey:@"course"];
    
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end

Fetching data from core data

Add this code in ViewController.m file

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // Fetch the studentsInfo from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    studentsArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
    
    [tabelViewStudents reloadData];
}

- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

Firstly viewWillAppear() method gets called. In this method we first get reference to managedObjectContext . Then we got the refrenece to fetchRequest which refers to an entity Student. Finally, executeFetchRequest is invoked to retrive the data from database. Its similar to Select query in relational database system.

#pragma mark - Table View Delegates
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return studentsArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [tabelViewStudents dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    // Configure the cell...
    NSManagedObject *studentsInfo = [studentsArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@ (%@)", [studentsInfo valueForKey:@"name"],[studentsInfo valueForKey:@"course"]]];
        
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

Fetching data from NSManagedObjectContext is similar to fetching data from NSDictionary. In dictionary, we get the value of key using valueForKey method. Similarly, in managed object context you can grab the attribute value using valueForKey method.

Final ViewController.m file looks like this,

#import "ViewController.h"
#import "CoreDataDetailsViewController.h"
#import <CoreData/CoreData.h>
@interface ViewController() <UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *studentsArray;
    UITableView *tabelViewStudents;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    /* give title to navigation bar */
    self.navigationItem.title = @"Codzify";

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(addButtonClicked)];
 
    studentsArray = [[NSMutableArray alloc]init];
    
    tabelViewStudents = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view  addSubview:tabelViewStudents];
    tabelViewStudents.separatorStyle = UITableViewCellSeparatorStyleNone;
    tabelViewStudents.delegate = self;
    tabelViewStudents.dataSource = self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // Fetch the studentsInfo from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    studentsArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
    
    [tabelViewStudents reloadData];
}
- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

#pragma mark - Table View Delegates
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return studentsArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [tabelViewStudents dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    // Configure the cell...
    NSManagedObject *studentsInfo = [studentsArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@ (%@)", [studentsInfo valueForKey:@"name"],[studentsInfo valueForKey:@"course"]]];
        
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}


#pragma mark - Actions
-(void)addButtonClicked
{
    NSLog(@"Add Button Clicked");
    CoreDataDetailsViewController *coreDataController = [[CoreDataDetailsViewController alloc]init];
    [self.navigationController pushViewController:coreDataController animated:YES];
}

@end

Output :-