SlideShare a Scribd company logo
Pulling back the curtain on
         Core Data
             Chris Mar
         Spree Commerce
          http://cmar.me
Chris Mar

• Spree Commerce

• iOS and Rails Developer

• @cmar

• Grassy Knoll Apps - Redskins
  Radar
Goal
Pull back the curtain on Core Data so
 you will use it on your next project
             without fear!




(we’ll focus on concepts, not a tutorial)
Core Data

• Object Relational Mapping
• Gives you access to a database without using sql
  or parsing results

• Cocoa API with XCode tooling to assist you

• Hibernate for Java, ActiveRecord for Rails
Storage Types
• SQLite Database

• XML

• In-Memory




              we’ll focus on SQLite
NSManagedObject
•   Row from the database

•   Key-Value coding for fields

•   Optionally subclass

•   Fetched from NSManagedObjectContext



                    [employee valueForKey:@"name"];
Managed Objects
    object1                                  object2




    object1                                  object2




               NSManagedObjectContext

              NSPersistentStoreCoordinator


                NSManagedObjectModel




    object1


                    SQLite Database
FetchRequest for
                      NSManagedObjects
NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:[NSEntityDescription entityForName:@"Order"
                 inManagedObjectContext:self.managedObjectContext]];

[request setPredicate:[NSPredicate
                predicateWithFormat:@"name like %@", @"*7*"]];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];

self.orders = [self.managedObjectContext
                 executeFetchRequest:request error:&error];

[sortDescriptor release];
[sortDescriptors release];
[request release];
The Big 3
 NSManagedObjectContext




NSPersistentStoreCoordinator       sqlite




  NSManagedObjectModel         .xcdatamodel
NSManagedObjectContext


• Object space for Managed Objects

• Fetches from Persistent Store

• Exclusive to a single thread

• Commit and Discard Changes
NSManagedObjectContext
                                    (lazy loaded in AppDelegate)

- (NSManagedObjectContext *)managedObjectContext
{
   if (__managedObjectContext != nil)
   {
       return __managedObjectContext;
   }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}
NSPersistentStoreCoordinator


• Manages connections to stores

• Maps data model to database

• Handles many stores

• Shared between threads
NSPersistentStoreCoordinator
                                  (lazy loaded in AppDelegate)

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
   if (__persistentStoreCoordinator != nil)
   {
       return __persistentStoreCoordinator;
   }

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

  NSError *error = nil;
  __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                    initWithManagedObjectModel:[self managedObjectModel]];

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

   return __persistentStoreCoordinator;
   }
NSManagedObjectModel

• Definition of database schema

• Describes entity objects in store

• Predefined Queries - Fetch Requests

• Relationships between entities
NSManagedObjectModel
                                   (lazy loaded in AppDelegate)



- (NSManagedObjectModel *)managedObjectModel
{
   if (__managedObjectModel != nil)
   {
       return __managedObjectModel;
   }

    NSURL *modelURL = [[NSBundle mainBundle]
          URLForResource:@"MyApp" withExtension:@"momd"];

    __managedObjectModel = [[NSManagedObjectModel alloc]
                    initWithContentsOfURL:modelURL];

    return __managedObjectModel;
}
NSManagedObjectModel
    XCode Editor
Insert new
                   NSManagedObject
NSManagedObject *car = [NSEntityDescription insertNewObjectForEntityForName:@"Car”
            inManagedObjectContext:self.managedObjectContext];

[car setValue:@"Jeep" forKey:@"name"];

//Save the whole context which will save all the objects in it
NSError *error = nil;
if ([self.managedObjectContext save:&error]) {
     NSLog(@"Saved");
} else {
     NSLog(@"Error saving %@", [error localizedDescription]);
}
Threads
                                   Pass ID between threads




               Thread1                                                  Thread2




Object id=1                                                                         Object id=1




  Object                                                                              Object
              NSManagedObjectContext                       NSManagedObjectContext
   id=1                                                                                id=1




                                  NSPersistentStoreCoordinator




                                        SQLite Database




                                          Object id=1
Memory Usage
self.orders = [self.managedObjectContext executeFetchRequest:request error:&error];




         •   Load into an Array

         • All in memory

         • Updates

         • Fast and Easy for small tables
NSFetchedResultsController


• Efficiently backs a UITableView

• Reduces memory usage

• Caches results

• Updates table for changes
NSFetchedResultsController

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController
alloc]
initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext
sectionNameKeyPath:nil cacheName:@"Root"];
The Big Picture
                                                              UITableView
                                            NSManagedObject
NSFetchedResultsController
                                            NSManagedObject   iPhone
                                            NSManagedObject   iPod touch
                                            NSManagedObject
                                                              iPad
                                            NSManagedObject
 NSManagedObjectContext                                       Steve Jobs Rocks




NSPersistentStoreCoordinator       sqlite




  NSManagedObjectModel         .xcdatamodel
Relationships
• to-one
 •   NSManagedObject *manager = [employee valueForKey:@”manager”];




• to-many
 •   NSSet *directReports = [manager valueForKey:@”directReports”];




• Define inverses for data integrity
• Delete Rules - nullify, cascade, deny
Fetched Properties

• Lazy loaded query relationship

• Sorted

• Predicate - filtered

• “Give a list of direct reports that begin with the
  letter C”
Fetch Requests

• Uses NSPredicate for Where clause
• Uses NSSortDescriptor for Order By clause
• Can be saved with Managed Object Model
  [fetchRequestTemplateForName]
Predicates

•   [NSPredicate predicateWithFormat:@"name CONTAINS[c] %@", searchText];

•   @"name BETWEEN %@", [NSArray arrayWithObjects:@”a”,@”b”,nil]

•   MATCHES for regex

•   CONTAINS[c] for case insenstivity

•   AND, OR, NOT
Default Project with Core

                                   1. [awakeFromNib]
         AppDelegate                                             RootViewController
                               set managedObjectContext




   2. [managedObjectContext]                                  3. [cellForRowAtIndexPath]
           lazy load                                      lazy load fetchedResultsController




   NSManagedObjectContext                                     fetchedResultsController
SQLite Tables
Z_PRIMARYKEY
Preloaded Database
• Load up database using Base
• Base lets you import csv
• Make sure you set the primary keys
• On start check for existence, then copy it over
Preloading Database
NSString *storePath = [[self applicationDocumentsDirectory]
    stringByAppendingPathComponent: @"products.sqlite"];
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
 
// Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
    NSString *defaultStorePath = [[NSBundle mainBundle]
        pathForResource:@"preloaded_products" ofType:@"sqlite"];
    if (defaultStorePath) {
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath
error:NULL];
    }
}
FMDB
• Objective-C wrapper for SQLite

• Direct access

• Low overhead

• Great for simple data needs

• https://github.com/ccgus/fmdb
FMDB Example
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/my.db"];
[db open]
FMResultSet *rs = [db executeQuery:@"select * from orders where customer_id = ?",
@"1000"];

    [rs intForColumn:@"c"],
    [rs stringForColumn:@"b"],
    [rs dateForColumn:@"d"],
    [rs doubleForColumn:@"e"]);
}
[rs close];
[db close];
Links
•   http://www.raywenderlich.com/934/core-data-
    tutorial-getting-started

• http://menial.co.uk/software/base/
• https://github.com/ccgus/fmdb
Thank You!




 @cmar on twitter
  http://cmar.me

More Related Content

What's hot (20)

PDF
ERGroupware
WO Community
 
PDF
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Thorben Janssen
 
PDF
iOS for ERREST - alternative version
WO Community
 
PDF
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
PDF
Client Server Communication on iOS
Make School
 
PDF
CDI 2.0 Deep Dive
Thorben Janssen
 
KEY
Node js mongodriver
christkv
 
PPTX
Google cloud datastore driver for Google Apps Script DB abstraction
Bruce McPherson
 
PDF
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
PDF
REST/JSON/CoreData Example Code - A Tour
Carl Brown
 
PDF
Symfony2 from the Trenches
Jonathan Wage
 
PPTX
Indexing and Query Optimization
MongoDB
 
PDF
Database madness with_mongoengine_and_sql_alchemy
Jaime Buelta
 
PPTX
Dbabstraction
Bruce McPherson
 
PPTX
Indexing & Query Optimization
MongoDB
 
PDF
20120121
komarineko
 
PDF
Utopia Kindgoms scaling case: From 4 to 50K users
Jaime Buelta
 
PDF
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
PDF
Drupal 8: Fields reborn
Pablo López Escobés
 
PPTX
Django - sql alchemy - jquery
Mohammed El Rafie Tarabay
 
ERGroupware
WO Community
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Thorben Janssen
 
iOS for ERREST - alternative version
WO Community
 
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Client Server Communication on iOS
Make School
 
CDI 2.0 Deep Dive
Thorben Janssen
 
Node js mongodriver
christkv
 
Google cloud datastore driver for Google Apps Script DB abstraction
Bruce McPherson
 
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
REST/JSON/CoreData Example Code - A Tour
Carl Brown
 
Symfony2 from the Trenches
Jonathan Wage
 
Indexing and Query Optimization
MongoDB
 
Database madness with_mongoengine_and_sql_alchemy
Jaime Buelta
 
Dbabstraction
Bruce McPherson
 
Indexing & Query Optimization
MongoDB
 
20120121
komarineko
 
Utopia Kindgoms scaling case: From 4 to 50K users
Jaime Buelta
 
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
Drupal 8: Fields reborn
Pablo López Escobés
 
Django - sql alchemy - jquery
Mohammed El Rafie Tarabay
 

Viewers also liked (17)

PDF
Интуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Глеб Тарасов
 
PPTX
MVVMCross da Windows Phone a Windows 8 passando per Android e iOS
Dan Ardelean
 
PDF
From Ruby on Rails to RubyMotion - Writing your First iOS App with RubyMotion
Michael Denomy
 
KEY
RubyMotion
Mark
 
PDF
iOS: A Broad Overview
Chris Farrell
 
PDF
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
smn-automate
 
PDF
[Srijan Wednesday Webinars] Building Full-Fledged Native Apps Using RubyMotion
Srijan Technologies
 
PDF
Introduction à l'Agilité
VINOT Bernard
 
PDF
Rapport de stage de fin d'etude l3 angelito & hasina
Angelito Mandimbihasina
 
PPTX
Conception et réalisation du module agenda partagé pour une solution de télés...
Toufik Atba
 
PPTX
Cisco Live Milan 2015 - BGP advance
Bertrand Duvivier
 
PPTX
Exposé 1
Hibatallah Aouadni
 
PPTX
Presentation pfe application de pointage ASP.NET
Meher Zayani
 
PDF
Seminaire Borland UML (2003)
Pascal Roques
 
PPTX
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Riadh K.
 
PPTX
gestion de magasin vente matériels informatique
Oussama Yoshiki
 
Интуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Глеб Тарасов
 
MVVMCross da Windows Phone a Windows 8 passando per Android e iOS
Dan Ardelean
 
From Ruby on Rails to RubyMotion - Writing your First iOS App with RubyMotion
Michael Denomy
 
RubyMotion
Mark
 
iOS: A Broad Overview
Chris Farrell
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
smn-automate
 
[Srijan Wednesday Webinars] Building Full-Fledged Native Apps Using RubyMotion
Srijan Technologies
 
Introduction à l'Agilité
VINOT Bernard
 
Rapport de stage de fin d'etude l3 angelito & hasina
Angelito Mandimbihasina
 
Conception et réalisation du module agenda partagé pour une solution de télés...
Toufik Atba
 
Cisco Live Milan 2015 - BGP advance
Bertrand Duvivier
 
Presentation pfe application de pointage ASP.NET
Meher Zayani
 
Seminaire Borland UML (2003)
Pascal Roques
 
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Riadh K.
 
gestion de magasin vente matériels informatique
Oussama Yoshiki
 
Ad

Similar to iOSDevCamp 2011 Core Data (20)

ODP
MobileCity:Core Data
Allan Davis
 
PPT
Core Data Migration
Monica Kurup
 
PPT
Connecting to a REST API in iOS
gillygize
 
PDF
Core Data with Swift 3.0
Korhan Bircan
 
PPT
Core data optimization
Gagan Vishal Mishra
 
PDF
Intro to Core Data
Make School
 
PDF
Infinum iOS Talks S01E02 - Things every iOS developer should know about Core ...
Denis_infinum
 
PPTX
Core Data Performance Guide Line
Gagan Vishal Mishra
 
PDF
CoreData Best Practices (2021)
deeje cooley
 
PPTX
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
Mail.ru Group
 
PDF
Developing iOS REST Applications
lmrei
 
KEY
Data perisistance i_os
Michał Tuszyński
 
PDF
Lean React - Patterns for High Performance [ploneconf2017]
Devon Bernard
 
PDF
10 tips for a reusable architecture
Jorge Ortiz
 
KEY
Week3
Will Gaybrick
 
PPTX
Real World MVC
James Johnson
 
PPTX
iOS Beginners Lesson 4
Calvin Cheng
 
KEY
Taking a Test Drive
Graham Lee
 
ODP
Slickdemo
Knoldus Inc.
 
PDF
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
ITGinGer
 
MobileCity:Core Data
Allan Davis
 
Core Data Migration
Monica Kurup
 
Connecting to a REST API in iOS
gillygize
 
Core Data with Swift 3.0
Korhan Bircan
 
Core data optimization
Gagan Vishal Mishra
 
Intro to Core Data
Make School
 
Infinum iOS Talks S01E02 - Things every iOS developer should know about Core ...
Denis_infinum
 
Core Data Performance Guide Line
Gagan Vishal Mishra
 
CoreData Best Practices (2021)
deeje cooley
 
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
Mail.ru Group
 
Developing iOS REST Applications
lmrei
 
Data perisistance i_os
Michał Tuszyński
 
Lean React - Patterns for High Performance [ploneconf2017]
Devon Bernard
 
10 tips for a reusable architecture
Jorge Ortiz
 
Real World MVC
James Johnson
 
iOS Beginners Lesson 4
Calvin Cheng
 
Taking a Test Drive
Graham Lee
 
Slickdemo
Knoldus Inc.
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
ITGinGer
 
Ad

Recently uploaded (20)

PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
July Patch Tuesday
Ivanti
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 

iOSDevCamp 2011 Core Data

  • 1. Pulling back the curtain on Core Data Chris Mar Spree Commerce http://cmar.me
  • 2. Chris Mar • Spree Commerce • iOS and Rails Developer • @cmar • Grassy Knoll Apps - Redskins Radar
  • 3. Goal Pull back the curtain on Core Data so you will use it on your next project without fear! (we’ll focus on concepts, not a tutorial)
  • 4. Core Data • Object Relational Mapping • Gives you access to a database without using sql or parsing results • Cocoa API with XCode tooling to assist you • Hibernate for Java, ActiveRecord for Rails
  • 5. Storage Types • SQLite Database • XML • In-Memory we’ll focus on SQLite
  • 6. NSManagedObject • Row from the database • Key-Value coding for fields • Optionally subclass • Fetched from NSManagedObjectContext [employee valueForKey:@"name"];
  • 7. Managed Objects object1 object2 object1 object2 NSManagedObjectContext NSPersistentStoreCoordinator NSManagedObjectModel object1 SQLite Database
  • 8. FetchRequest for NSManagedObjects NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Order" inManagedObjectContext:self.managedObjectContext]]; [request setPredicate:[NSPredicate predicateWithFormat:@"name like %@", @"*7*"]]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; self.orders = [self.managedObjectContext executeFetchRequest:request error:&error]; [sortDescriptor release]; [sortDescriptors release]; [request release];
  • 9. The Big 3 NSManagedObjectContext NSPersistentStoreCoordinator sqlite NSManagedObjectModel .xcdatamodel
  • 10. NSManagedObjectContext • Object space for Managed Objects • Fetches from Persistent Store • Exclusive to a single thread • Commit and Discard Changes
  • 11. NSManagedObjectContext (lazy loaded in AppDelegate) - (NSManagedObjectContext *)managedObjectContext { if (__managedObjectContext != nil) { return __managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { __managedObjectContext = [[NSManagedObjectContext alloc] init]; [__managedObjectContext setPersistentStoreCoordinator:coordinator]; } return __managedObjectContext; }
  • 12. NSPersistentStoreCoordinator • Manages connections to stores • Maps data model to database • Handles many stores • Shared between threads
  • 13. NSPersistentStoreCoordinator (lazy loaded in AppDelegate) - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (__persistentStoreCoordinator != nil) { return __persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MyApp.sqlite"]; NSError *error = nil; __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { } return __persistentStoreCoordinator; }
  • 14. NSManagedObjectModel • Definition of database schema • Describes entity objects in store • Predefined Queries - Fetch Requests • Relationships between entities
  • 15. NSManagedObjectModel (lazy loaded in AppDelegate) - (NSManagedObjectModel *)managedObjectModel { if (__managedObjectModel != nil) { return __managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyApp" withExtension:@"momd"]; __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return __managedObjectModel; }
  • 16. NSManagedObjectModel XCode Editor
  • 17. Insert new NSManagedObject NSManagedObject *car = [NSEntityDescription insertNewObjectForEntityForName:@"Car” inManagedObjectContext:self.managedObjectContext]; [car setValue:@"Jeep" forKey:@"name"]; //Save the whole context which will save all the objects in it NSError *error = nil; if ([self.managedObjectContext save:&error]) { NSLog(@"Saved"); } else { NSLog(@"Error saving %@", [error localizedDescription]); }
  • 18. Threads Pass ID between threads Thread1 Thread2 Object id=1 Object id=1 Object Object NSManagedObjectContext NSManagedObjectContext id=1 id=1 NSPersistentStoreCoordinator SQLite Database Object id=1
  • 19. Memory Usage self.orders = [self.managedObjectContext executeFetchRequest:request error:&error]; • Load into an Array • All in memory • Updates • Fast and Easy for small tables
  • 20. NSFetchedResultsController • Efficiently backs a UITableView • Reduces memory usage • Caches results • Updates table for changes
  • 21. NSFetchedResultsController NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
  • 22. The Big Picture UITableView NSManagedObject NSFetchedResultsController NSManagedObject iPhone NSManagedObject iPod touch NSManagedObject iPad NSManagedObject NSManagedObjectContext Steve Jobs Rocks NSPersistentStoreCoordinator sqlite NSManagedObjectModel .xcdatamodel
  • 23. Relationships • to-one • NSManagedObject *manager = [employee valueForKey:@”manager”]; • to-many • NSSet *directReports = [manager valueForKey:@”directReports”]; • Define inverses for data integrity • Delete Rules - nullify, cascade, deny
  • 24. Fetched Properties • Lazy loaded query relationship • Sorted • Predicate - filtered • “Give a list of direct reports that begin with the letter C”
  • 25. Fetch Requests • Uses NSPredicate for Where clause • Uses NSSortDescriptor for Order By clause • Can be saved with Managed Object Model [fetchRequestTemplateForName]
  • 26. Predicates • [NSPredicate predicateWithFormat:@"name CONTAINS[c] %@", searchText]; • @"name BETWEEN %@", [NSArray arrayWithObjects:@”a”,@”b”,nil] • MATCHES for regex • CONTAINS[c] for case insenstivity • AND, OR, NOT
  • 27. Default Project with Core 1. [awakeFromNib] AppDelegate RootViewController set managedObjectContext 2. [managedObjectContext] 3. [cellForRowAtIndexPath] lazy load lazy load fetchedResultsController NSManagedObjectContext fetchedResultsController
  • 30. Preloaded Database • Load up database using Base • Base lets you import csv • Make sure you set the primary keys • On start check for existence, then copy it over
  • 31. Preloading Database NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"products.sqlite"]; NSURL *storeUrl = [NSURL fileURLWithPath:storePath];   // Put down default db if it doesn't already exist NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:storePath]) { NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"preloaded_products" ofType:@"sqlite"]; if (defaultStorePath) { [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL]; } }
  • 32. FMDB • Objective-C wrapper for SQLite • Direct access • Low overhead • Great for simple data needs • https://github.com/ccgus/fmdb
  • 33. FMDB Example FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/my.db"]; [db open] FMResultSet *rs = [db executeQuery:@"select * from orders where customer_id = ?", @"1000"];     [rs intForColumn:@"c"],     [rs stringForColumn:@"b"],     [rs dateForColumn:@"d"],     [rs doubleForColumn:@"e"]); } [rs close]; [db close];
  • 34. Links • http://www.raywenderlich.com/934/core-data- tutorial-getting-started • http://menial.co.uk/software/base/ • https://github.com/ccgus/fmdb
  • 35. Thank You! @cmar on twitter http://cmar.me

Editor's Notes