SlideShare ist ein Scribd-Unternehmen logo
1 von 53
INTRODUCTION
TO CORE DATA
TO CORE DATA
Orlando iOS Developer Group
01/23/2013




 Scott Ahten                  AHTEN INDUSTRIES
Who Am I?


Scott Ahten, Ahten Industries
Technologist, iOS Developer
scott@ahtenindustries.com
Topics Covered

What is Core Data?
When should I use Core Data?
Framework overview
Using Core Data
Migrations
Threading & concurrency types
What is Core Data


Not a Database!
Not an Object Relational Mapping framework
What is Core Data

Object Persistence Framework
CRUD operations
Queries using NSPredicate
  Aggregate queries
Multiple persistent store
Available on iOS and Mac OS X Desktop
Persistent
Store Types
Store Types
Binary
In Memory
XML (Desktop Only)
SQLite
Custom Types
Core Data vs. SQLite
                         SQLite   Core Data
   Multiple Update        YES       NO
   Multiple Delete        YES       NO
Auto Populate Objects     NO        YES
    Custom SQL            YES       NO
      Automatic
Lightweight Migrations    NO        YES
       Speed              YES       YES
   Model Objects          NO        YES
When Should I
Use CoreData?
Use CoreData?
Wrong Question
When Shouldn’t I use Core Data?
Really Fast - Highly Optimized by Apple
All but trivial and special cases
You should be using Model objects
Core Data and MVC

    View
    View               Controller
                       Controller




             Model
             Model



           Core Data
Model Objects

NSManagedObject subclass
Lifecycle events
Validation
Faulting
Undo Support
Relationships
Core Data Framework
                             Application
                             Application


                         NSManagedObject
                         NSManagedObject


                      NSManageObjectContext
                      NSManageObjectContext


    NSPersistentStoreCoordinator
    NSPersistentStoreCoordinator       NSManageObjectModel
                                       NSManageObjectModel


                         NSPersistentStore
                         NSPersistentStore


     XML
     XML       SQLite
               SQLite      Binary
                           Binary     Memory
                                      Memory       Custom
                                                   Custom
Core Data Stack


Setup in App Delegate
Xcode Core Data template
NSPersistentStoreCoordinator




 Coordinates access to one or more persistent stores
 Managed Object Model
 Set store options
NSPersistentStoreCoordinator

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

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

  NSError *error = nil;
  _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self
managedObjectModel]];
  if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL
options:nil error:&error]) {
           NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
  }

    return _persistentStoreCoordinator;
}
NSPersistentStoreCoordinator

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

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

  NSError *error = nil;
  _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self
managedObjectModel]];
  if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL
options:nil error:&error]) {
           NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
  }

    return _persistentStoreCoordinator;
}
NSPersistentStoreCoordinator

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

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

  NSError *error = nil;
  _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self
managedObjectModel]];
  if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL
options:nil error:&error]) {
           NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
  }

    return _persistentStoreCoordinator;
}
NSPersistentStoreCoordinator

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

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

  NSError *error = nil;
  _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self
managedObjectModel]];
  if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL
options:nil error:&error]) {
           NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
  }

    return _persistentStoreCoordinator;
}
NSManagedObjectModel


 Schema for Models
 Entities, properties, relationships, etc.
 Validations
 Fetch Requests
 Configurations
 Objective-C Subclass
NSManagedObjectModel
Attribute Types
 Integer Types
 Decimal
 Double
 Float
 String
 Boolean
 Date
 Binary Data
Other Types?



 Serialize to NSData via NSCoder
 Value Transformer and Transformable type
   Opaque to Queries
 NSManagedObject subclass
Attribute Options



 Transient
 Optional
 Indexed
 Default Values
 Store in external record file (iOS 5 >=)
Relationships

 NSSet, not NSArray
 One to one
 One to many and many to many
   Minimum and maximum count
   Ordered returned NSOrderedSet (iOS 5>=)
 Delete Rules
   Nullify, Cascade, Deny
NSManagedObjectModel


// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Example_App" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}
NSManagedObjectModel


// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Example_App" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}
NSManagedObjectModel


// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Example_App" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}
NSManagedObjectContext

Scratch Pad for Entities
Queried objects are pulled into context
  Can be Faulted
Entities inserted into context
Changes are not persisted until calling save:
NSManagedObjectContext

Not thread safe!
One context per thread
More than one context per coordinator
  Merge notifications
Concurrency Types (iOS 5>=)
  Blocks, GCD queues
NSManagedObjectContext

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

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

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

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

Save occurs per context
Saves changes to persistent store
Should save on applicationWillTerminate:
Can be reset to discard changes
Saving


- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
   if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
       // Replace this implementation with code to handle the error appropriately.
       }
    }
}
NSManagedObject

Represents an entity in your model
Superclass of managed object subclasses
Access attributes via KVC/KVO and properties
Pass NSManagedObjectIDs between threads
Xcode can generate subclass with accessors
Can be a fault
Querying Entites
NSPredicate
Rich query syntax
Aggregate property values
Compound predicates
Queries can return faulted entities based on result
type
Batch size
Faults

Only object ID
Performance & memory
Include specific properties
Prefetch relationships
Querying Entites
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

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


NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error]
mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error.
}
Querying Entites
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

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


NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error]
mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error.
}
Querying Entites
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

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


NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error]
mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error.
}
Querying Entites
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

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


NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error]
mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error.
}
Predicates

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"grade > %d", 7];



NSPredicate *testForTrue =
  [NSPredicate predicateWithFormat:@"anAttribute == YES"];



NSPredicate *predicate = [NSPredicate
  predicateWithFormat:@"(lastName like[cd] %@) AND (birthday > %@)",
          lastNameSearchString, birthdaySearchDate];



[fetchRequest setPredicate:predicate];
Inserting Entities


 Insert into managed object context
 Entities are not yet persisted until context is saved
Inserting Entities

- (void)insertNewObject:(id)sender
{
   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
   NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
   NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name]
inManagedObjectContext:context];

  // If appropriate, configure the new managed object.
  // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the
template.
  [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
         // Replace this implementation with code to handle the error appropriately.
    }
}
Inserting Entities

- (void)insertNewObject:(id)sender
{
   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
   NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
   NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name]
inManagedObjectContext:context];

  // If appropriate, configure the new managed object.
  // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the
template.
  [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
         // Replace this implementation with code to handle the error appropriately.
    }
}
Inserting Entities

- (void)insertNewObject:(id)sender
{
   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
   NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
   NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name]
inManagedObjectContext:context];

  // If appropriate, configure the new managed object.
  // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the
template.
  [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
         // Replace this implementation with code to handle the error appropriately.
    }
}
Inserting Entities

- (void)insertNewObject:(id)sender
{
   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
   NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
   NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name]
inManagedObjectContext:context];

  // If appropriate, configure the new managed object.
  // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the
template.
  [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
         // Replace this implementation with code to handle the error appropriately.
    }
}
Deleting Entites

 Entities are marked as deleted
 No longer returned in queries
 Not actually deleted until context is saved
 Deletes can be discarded before save by discarding
 or resetting the context
Deleting Entites


- (void)deleteEvent:(NSManagedObject*)event
{
   NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

    NSError *error = nil;
    [managedObjectContext deleteObject: event];
    if (![managedObjectContext save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
    }
}
Updating Entities


Same as insert
Change properties and save context
Updates can be discarded before save by discarding
or resetting the context
Migrations

Schemas change
Create new model version
Automatic lightweight migration
Manual migration
Not all changes require migration
  Validation, default values, Objective-C class
Concurency Types
iOS 5 >=
NSConfinementConcurrencyType
 Pre iOS 5 Concurrency
NSPrivateQueueConcurrencyType
 Private dispatch queue
NSMainQueueConcurrencyType
 Main Queue
Resources
Core Data Programming Guide
http://developer.apple.com/library/mac/#
documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html

Predicate Programming Guide
http://developer.apple.com/library/mac/#
documentation/Cocoa/Conceptual/Predicates/predicates.html

Grand Central Dispatch (GCD)
http://developer.apple.com/library/ios/#
documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/referen
ce.html
Resources

Magical Record
http://developer.apple.com/library/mac/#
documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html

Multi-Context Core Data
http://www.cocoanetics.com/2012/07/multi-context-coredata/

Core Data Editor
http://christian-kienle.de/CoreDataEditor
Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
Kaniska Mandal
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
Ram132
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 
Introduction to Struts
Introduction to StrutsIntroduction to Struts
Introduction to Struts
elliando dias
 

Was ist angesagt? (20)

To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
White Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application ArchitectureWhite Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application Architecture
 
OR Mapping- nhibernate Presentation
OR Mapping- nhibernate PresentationOR Mapping- nhibernate Presentation
OR Mapping- nhibernate Presentation
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
CDI 2.0 Deep Dive
CDI 2.0 Deep DiveCDI 2.0 Deep Dive
CDI 2.0 Deep Dive
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Kabukiza.tech 1 LT - ScalikeJDBC-Async & Skinny Framework #kbkz_tech
Kabukiza.tech 1 LT - ScalikeJDBC-Async & Skinny Framework #kbkz_techKabukiza.tech 1 LT - ScalikeJDBC-Async & Skinny Framework #kbkz_tech
Kabukiza.tech 1 LT - ScalikeJDBC-Async & Skinny Framework #kbkz_tech
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Multi-threaded CoreData Done Right
Multi-threaded CoreData Done RightMulti-threaded CoreData Done Right
Multi-threaded CoreData Done Right
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Cocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollersCocoa heads testing and viewcontrollers
Cocoa heads testing and viewcontrollers
 
ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for Beginners
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Introduction to Struts
Introduction to StrutsIntroduction to Struts
Introduction to Struts
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 

Andere mochten auch

Adaptación OpenGeo Suite Castellbisbal
Adaptación OpenGeo Suite CastellbisbalAdaptación OpenGeo Suite Castellbisbal
Adaptación OpenGeo Suite Castellbisbal
Oscar Fonts
 
Cuentos Sobre Alan Garcia
Cuentos Sobre Alan GarciaCuentos Sobre Alan Garcia
Cuentos Sobre Alan Garcia
alphasoundd
 
Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...
Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...
Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...
mfrancis
 

Andere mochten auch (20)

Anuncio BOPBUR Subasta Licitacion Coto Caza Espinosa de los Monteros
Anuncio BOPBUR Subasta Licitacion Coto Caza Espinosa de los MonterosAnuncio BOPBUR Subasta Licitacion Coto Caza Espinosa de los Monteros
Anuncio BOPBUR Subasta Licitacion Coto Caza Espinosa de los Monteros
 
Chapter 8 levinas
Chapter 8   levinasChapter 8   levinas
Chapter 8 levinas
 
Use of magnets in orthodontics /certified fixed orthodontic courses by Indi...
Use  of magnets in orthodontics  /certified fixed orthodontic courses by Indi...Use  of magnets in orthodontics  /certified fixed orthodontic courses by Indi...
Use of magnets in orthodontics /certified fixed orthodontic courses by Indi...
 
Kommunalprogramm 2014 Magazin
Kommunalprogramm 2014 MagazinKommunalprogramm 2014 Magazin
Kommunalprogramm 2014 Magazin
 
John hyman joins cheyne hedge fund
John hyman joins cheyne hedge fundJohn hyman joins cheyne hedge fund
John hyman joins cheyne hedge fund
 
Como implementar nuevas evaluaciones
Como implementar nuevas evaluacionesComo implementar nuevas evaluaciones
Como implementar nuevas evaluaciones
 
Biomoleculas
BiomoleculasBiomoleculas
Biomoleculas
 
Adaptación OpenGeo Suite Castellbisbal
Adaptación OpenGeo Suite CastellbisbalAdaptación OpenGeo Suite Castellbisbal
Adaptación OpenGeo Suite Castellbisbal
 
Unic pag internas repositorio del programa apartado investigación
Unic pag internas repositorio del programa apartado investigaciónUnic pag internas repositorio del programa apartado investigación
Unic pag internas repositorio del programa apartado investigación
 
Cuentos Sobre Alan Garcia
Cuentos Sobre Alan GarciaCuentos Sobre Alan Garcia
Cuentos Sobre Alan Garcia
 
Boletin nayarit mayo junio
Boletin nayarit mayo junioBoletin nayarit mayo junio
Boletin nayarit mayo junio
 
Plan estratégico del PROYECTO CALMARR
Plan estratégico del PROYECTO CALMARRPlan estratégico del PROYECTO CALMARR
Plan estratégico del PROYECTO CALMARR
 
I Nvitacion Dia Dentista
I Nvitacion Dia DentistaI Nvitacion Dia Dentista
I Nvitacion Dia Dentista
 
Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...
Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...
Benefits of the OSGi Solution for Manufacturers and Service Providers - S Sch...
 
Ruth alvarez molina
Ruth alvarez molinaRuth alvarez molina
Ruth alvarez molina
 
UGC NET - JUNE-2010- PAPER-I-SET-W
UGC NET - JUNE-2010- PAPER-I-SET-WUGC NET - JUNE-2010- PAPER-I-SET-W
UGC NET - JUNE-2010- PAPER-I-SET-W
 
3 m deber direccion E
3 m deber direccion E3 m deber direccion E
3 m deber direccion E
 
Lesson Plan Kinder1
Lesson Plan Kinder1Lesson Plan Kinder1
Lesson Plan Kinder1
 
6 anticonceptiv-3
6 anticonceptiv-36 anticonceptiv-3
6 anticonceptiv-3
 
exercises Chapter 1 Energy, Enviroment and climate second edition
exercises Chapter 1 Energy, Enviroment and climate second edition exercises Chapter 1 Energy, Enviroment and climate second edition
exercises Chapter 1 Energy, Enviroment and climate second edition
 

Ähnlich wie Core data orlando i os dev group

Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
brandonsavage
 

Ähnlich wie Core data orlando i os dev group (20)

Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to 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
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 
Data perisistence in iOS
Data perisistence in iOSData perisistence in iOS
Data perisistence in iOS
 
Data perisistance i_os
Data perisistance i_osData perisistance i_os
Data perisistance i_os
 
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...
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
 
Mashup iOS - Core data
Mashup iOS - Core dataMashup iOS - Core data
Mashup iOS - Core data
 
10 tips for a reusable architecture
10 tips for a reusable architecture10 tips for a reusable architecture
10 tips for a reusable architecture
 
Make your Backbone Application dance
Make your Backbone Application danceMake your Backbone Application dance
Make your Backbone Application dance
 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better Option
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
 
Taking a Test Drive
Taking a Test DriveTaking a Test Drive
Taking a Test Drive
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN StackMongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
 

Mehr von Andrew Kozlik

Generating revenue with AdMob
Generating revenue with AdMobGenerating revenue with AdMob
Generating revenue with AdMob
Andrew Kozlik
 

Mehr von Andrew Kozlik (7)

Slack Development and You
Slack Development and YouSlack Development and You
Slack Development and You
 
3D Touch Implementation for Shortcuts and Peek/Pop Functionality
3D Touch Implementation for Shortcuts and Peek/Pop Functionality3D Touch Implementation for Shortcuts and Peek/Pop Functionality
3D Touch Implementation for Shortcuts and Peek/Pop Functionality
 
Leveraging parse.com for Speedy Development
Leveraging parse.com for Speedy DevelopmentLeveraging parse.com for Speedy Development
Leveraging parse.com for Speedy Development
 
How to start developing iOS apps
How to start developing iOS appsHow to start developing iOS apps
How to start developing iOS apps
 
Mwyf presentation
Mwyf presentationMwyf presentation
Mwyf presentation
 
Last Ace of Space Postmortem
Last Ace of Space PostmortemLast Ace of Space Postmortem
Last Ace of Space Postmortem
 
Generating revenue with AdMob
Generating revenue with AdMobGenerating revenue with AdMob
Generating revenue with AdMob
 

Kürzlich hochgeladen

+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@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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...
 
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...
 
+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...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
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 ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 

Core data orlando i os dev group

  • 1. INTRODUCTION TO CORE DATA TO CORE DATA Orlando iOS Developer Group 01/23/2013 Scott Ahten AHTEN INDUSTRIES
  • 2. Who Am I? Scott Ahten, Ahten Industries Technologist, iOS Developer scott@ahtenindustries.com
  • 3. Topics Covered What is Core Data? When should I use Core Data? Framework overview Using Core Data Migrations Threading & concurrency types
  • 4. What is Core Data Not a Database! Not an Object Relational Mapping framework
  • 5. What is Core Data Object Persistence Framework CRUD operations Queries using NSPredicate Aggregate queries Multiple persistent store Available on iOS and Mac OS X Desktop
  • 6. Persistent Store Types Store Types Binary In Memory XML (Desktop Only) SQLite Custom Types
  • 7. Core Data vs. SQLite SQLite Core Data Multiple Update YES NO Multiple Delete YES NO Auto Populate Objects NO YES Custom SQL YES NO Automatic Lightweight Migrations NO YES Speed YES YES Model Objects NO YES
  • 8. When Should I Use CoreData? Use CoreData? Wrong Question When Shouldn’t I use Core Data? Really Fast - Highly Optimized by Apple All but trivial and special cases You should be using Model objects
  • 9. Core Data and MVC View View Controller Controller Model Model Core Data
  • 10. Model Objects NSManagedObject subclass Lifecycle events Validation Faulting Undo Support Relationships
  • 11. Core Data Framework Application Application NSManagedObject NSManagedObject NSManageObjectContext NSManageObjectContext NSPersistentStoreCoordinator NSPersistentStoreCoordinator NSManageObjectModel NSManageObjectModel NSPersistentStore NSPersistentStore XML XML SQLite SQLite Binary Binary Memory Memory Custom Custom
  • 12. Core Data Stack Setup in App Delegate Xcode Core Data template
  • 13. NSPersistentStoreCoordinator Coordinates access to one or more persistent stores Managed Object Model Set store options
  • 14. NSPersistentStoreCoordinator // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Example_App.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; }
  • 15. NSPersistentStoreCoordinator // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Example_App.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; }
  • 16. NSPersistentStoreCoordinator // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Example_App.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; }
  • 17. NSPersistentStoreCoordinator // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Example_App.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; }
  • 18. NSManagedObjectModel Schema for Models Entities, properties, relationships, etc. Validations Fetch Requests Configurations Objective-C Subclass
  • 20. Attribute Types Integer Types Decimal Double Float String Boolean Date Binary Data
  • 21. Other Types? Serialize to NSData via NSCoder Value Transformer and Transformable type Opaque to Queries NSManagedObject subclass
  • 22. Attribute Options Transient Optional Indexed Default Values Store in external record file (iOS 5 >=)
  • 23. Relationships NSSet, not NSArray One to one One to many and many to many Minimum and maximum count Ordered returned NSOrderedSet (iOS 5>=) Delete Rules Nullify, Cascade, Deny
  • 24. NSManagedObjectModel // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Example_App" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; }
  • 25. NSManagedObjectModel // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Example_App" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; }
  • 26. NSManagedObjectModel // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Example_App" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; }
  • 27. NSManagedObjectContext Scratch Pad for Entities Queried objects are pulled into context Can be Faulted Entities inserted into context Changes are not persisted until calling save:
  • 28. NSManagedObjectContext Not thread safe! One context per thread More than one context per coordinator Merge notifications Concurrency Types (iOS 5>=) Blocks, GCD queues
  • 29. NSManagedObjectContext // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. - (NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext; }
  • 30. NSManagedObjectContext // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. - (NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext; }
  • 31. Saving Save occurs per context Saves changes to persistent store Should save on applicationWillTerminate: Can be reset to discard changes
  • 32. Saving - (void)saveContext { NSError *error = nil; NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != nil) { if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { // Replace this implementation with code to handle the error appropriately. } } }
  • 33. NSManagedObject Represents an entity in your model Superclass of managed object subclasses Access attributes via KVC/KVO and properties Pass NSManagedObjectIDs between threads Xcode can generate subclass with accessors Can be a fault
  • 34. Querying Entites NSPredicate Rich query syntax Aggregate property values Compound predicates Queries can return faulted entities based on result type Batch size
  • 35. Faults Only object ID Performance & memory Include specific properties Prefetch relationships
  • 36. Querying Entites NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. }
  • 37. Querying Entites NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. }
  • 38. Querying Entites NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. }
  • 39. Querying Entites NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. }
  • 40. Predicates NSPredicate *predicate = [NSPredicate predicateWithFormat:@"grade > %d", 7]; NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == YES"]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(lastName like[cd] %@) AND (birthday > %@)",         lastNameSearchString, birthdaySearchDate]; [fetchRequest setPredicate:predicate];
  • 41. Inserting Entities Insert into managed object context Entities are not yet persisted until context is saved
  • 42. Inserting Entities - (void)insertNewObject:(id)sender { NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"]; // Save the context. NSError *error = nil; if (![context save:&error]) { // Replace this implementation with code to handle the error appropriately. } }
  • 43. Inserting Entities - (void)insertNewObject:(id)sender { NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"]; // Save the context. NSError *error = nil; if (![context save:&error]) { // Replace this implementation with code to handle the error appropriately. } }
  • 44. Inserting Entities - (void)insertNewObject:(id)sender { NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"]; // Save the context. NSError *error = nil; if (![context save:&error]) { // Replace this implementation with code to handle the error appropriately. } }
  • 45. Inserting Entities - (void)insertNewObject:(id)sender { NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"]; // Save the context. NSError *error = nil; if (![context save:&error]) { // Replace this implementation with code to handle the error appropriately. } }
  • 46. Deleting Entites Entities are marked as deleted No longer returned in queries Not actually deleted until context is saved Deletes can be discarded before save by discarding or resetting the context
  • 47. Deleting Entites - (void)deleteEvent:(NSManagedObject*)event { NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSError *error = nil; [managedObjectContext deleteObject: event]; if (![managedObjectContext save:&error]) { // Replace this implementation with code to handle the error appropriately. } }
  • 48. Updating Entities Same as insert Change properties and save context Updates can be discarded before save by discarding or resetting the context
  • 49. Migrations Schemas change Create new model version Automatic lightweight migration Manual migration Not all changes require migration Validation, default values, Objective-C class
  • 50. Concurency Types iOS 5 >= NSConfinementConcurrencyType Pre iOS 5 Concurrency NSPrivateQueueConcurrencyType Private dispatch queue NSMainQueueConcurrencyType Main Queue
  • 51. Resources Core Data Programming Guide http://developer.apple.com/library/mac/# documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html Predicate Programming Guide http://developer.apple.com/library/mac/# documentation/Cocoa/Conceptual/Predicates/predicates.html Grand Central Dispatch (GCD) http://developer.apple.com/library/ios/# documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/referen ce.html
  • 52. Resources Magical Record http://developer.apple.com/library/mac/# documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html Multi-Context Core Data http://www.cocoanetics.com/2012/07/multi-context-coredata/ Core Data Editor http://christian-kienle.de/CoreDataEditor
  • 53. Q&A