SlideShare una empresa de Scribd logo
1 de 35
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

Más contenido relacionado

La actualidad más candente

iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
WO Community
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
MongoDB
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemy
Jaime Buelta
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
MongoDB
 

La actualidad más candente (20)

ERGroupware
ERGroupwareERGroupware
ERGroupware
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
CDI 2.0 Deep Dive
CDI 2.0 Deep DiveCDI 2.0 Deep Dive
CDI 2.0 Deep Dive
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstraction
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemy
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
20120121
2012012120120121
20120121
 
Utopia Kindgoms scaling case: From 4 to 50K users
Utopia Kindgoms scaling case: From 4 to 50K usersUtopia Kindgoms scaling case: From 4 to 50K users
Utopia Kindgoms scaling case: From 4 to 50K users
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Drupal 8: Fields reborn
Drupal 8: Fields rebornDrupal 8: Fields reborn
Drupal 8: Fields reborn
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 

Destacado

Интуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Интуит. Разработка приложений для iOS. Лекция 8. Работа с даннымиИнтуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Интуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Глеб Тарасов
 
MVVMCross da Windows Phone a Windows 8 passando per Android e iOS
MVVMCross da Windows Phone a Windows 8 passando per Android e iOSMVVMCross da Windows Phone a Windows 8 passando per Android e iOS
MVVMCross da Windows Phone a Windows 8 passando per Android e iOS
Dan Ardelean
 
iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad Overview
Chris Farrell
 
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Riadh K.
 
gestion de magasin vente matériels informatique
gestion de magasin vente matériels informatiquegestion de magasin vente matériels informatique
gestion de magasin vente matériels informatique
Oussama Yoshiki
 

Destacado (17)

Интуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Интуит. Разработка приложений для iOS. Лекция 8. Работа с даннымиИнтуит. Разработка приложений для iOS. Лекция 8. Работа с данными
Интуит. Разработка приложений для iOS. Лекция 8. Работа с данными
 
MVVMCross da Windows Phone a Windows 8 passando per Android e iOS
MVVMCross da Windows Phone a Windows 8 passando per Android e iOSMVVMCross da Windows Phone a Windows 8 passando per Android e iOS
MVVMCross da Windows Phone a Windows 8 passando per Android e iOS
 
From Ruby on Rails to RubyMotion - Writing your First iOS App with RubyMotion
From Ruby on Rails to RubyMotion - Writing your First iOS App with RubyMotionFrom Ruby on Rails to RubyMotion - Writing your First iOS App with RubyMotion
From Ruby on Rails to RubyMotion - Writing your First iOS App with RubyMotion
 
RubyMotion
RubyMotionRubyMotion
RubyMotion
 
iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad Overview
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
[Srijan Wednesday Webinars] Building Full-Fledged Native Apps Using RubyMotion
[Srijan Wednesday Webinars] Building Full-Fledged Native Apps Using RubyMotion[Srijan Wednesday Webinars] Building Full-Fledged Native Apps Using RubyMotion
[Srijan Wednesday Webinars] Building Full-Fledged Native Apps Using RubyMotion
 
Introduction à l'Agilité
Introduction à l'AgilitéIntroduction à l'Agilité
Introduction à l'Agilité
 
Rapport de stage de fin d'etude l3 angelito & hasina
Rapport de stage de fin d'etude l3 angelito & hasinaRapport de stage de fin d'etude l3 angelito & hasina
Rapport de stage de fin d'etude l3 angelito & hasina
 
Conception et réalisation du module agenda partagé pour une solution de télés...
Conception et réalisation du module agenda partagé pour une solution de télés...Conception et réalisation du module agenda partagé pour une solution de télés...
Conception et réalisation du module agenda partagé pour une solution de télés...
 
Uml
UmlUml
Uml
 
Cisco Live Milan 2015 - BGP advance
Cisco Live Milan 2015 - BGP advanceCisco Live Milan 2015 - BGP advance
Cisco Live Milan 2015 - BGP advance
 
Exposé 1
Exposé   1Exposé   1
Exposé 1
 
Presentation pfe application de pointage ASP.NET
Presentation pfe application de pointage ASP.NETPresentation pfe application de pointage ASP.NET
Presentation pfe application de pointage ASP.NET
 
Seminaire Borland UML (2003)
Seminaire Borland UML (2003)Seminaire Borland UML (2003)
Seminaire Borland UML (2003)
 
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
Rapport PFE : Développement D'une application de gestion des cartes de fidéli...
 
gestion de magasin vente matériels informatique
gestion de magasin vente matériels informatiquegestion de magasin vente matériels informatique
gestion de magasin vente matériels informatique
 

Similar a iOSDevCamp 2011 Core Data

MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core Data
Allan Davis
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
ITGinGer
 

Similar a iOSDevCamp 2011 Core Data (20)

MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core Data
 
Core Data Migration
Core Data MigrationCore Data Migration
Core Data Migration
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Infinum iOS Talks S01E02 - Things every iOS developer should know about Core ...
Infinum iOS Talks S01E02 - Things every iOS developer should know about Core ...Infinum iOS Talks S01E02 - Things every iOS developer should know about Core ...
Infinum iOS Talks S01E02 - Things every iOS developer should know about Core ...
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
 
CoreData Best Practices (2021)
CoreData Best Practices (2021)CoreData Best Practices (2021)
CoreData Best Practices (2021)
 
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
Data perisistance i_os
Data perisistance i_osData perisistance i_os
Data perisistance i_os
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]
 
10 tips for a reusable architecture
10 tips for a reusable architecture10 tips for a reusable architecture
10 tips for a reusable architecture
 
Week3
Week3Week3
Week3
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
iOS Beginners Lesson 4
iOS Beginners Lesson 4iOS Beginners Lesson 4
iOS Beginners Lesson 4
 
Taking a Test Drive
Taking a Test DriveTaking a Test Drive
Taking a Test Drive
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

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

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n