INTRODUCTIONTO CORE DATATO CORE DATAOrlando iOS Developer Group01/23/2013 Scott Ahten                  AHTEN INDUSTRIES
Who Am I?Scott Ahten, Ahten IndustriesTechnologist, iOS Developerscott@ahtenindustries.com
Topics CoveredWhat is Core Data?When should I use Core Data?Framework overviewUsing Core DataMigrationsThreading & concurr...
What is Core DataNot a Database!Not an Object Relational Mapping framework
What is Core DataObject Persistence FrameworkCRUD operationsQueries using NSPredicate  Aggregate queriesMultiple persisten...
PersistentStore TypesStore TypesBinaryIn MemoryXML (Desktop Only)SQLiteCustom Types
Core Data vs. SQLite                         SQLite   Core Data   Multiple Update        YES       NO   Multiple Delete   ...
When Should IUse CoreData?Use CoreData?Wrong QuestionWhen Shouldn’t I use Core Data?Really Fast - Highly Optimized by Appl...
Core Data and MVC    View    View               Controller                       Controller             Model             ...
Model ObjectsNSManagedObject subclassLifecycle eventsValidationFaultingUndo SupportRelationships
Core Data Framework                             Application                             Application                       ...
Core Data StackSetup in App DelegateXcode 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 doesnt a...
NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt a...
NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt a...
NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt a...
NSManagedObjectModel Schema for Models Entities, properties, relationships, etc. Validations Fetch Requests Configurations...
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 ...
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 NS...
NSManagedObjectModel// Returns the managed object model for the application.// If the model doesnt already exist, it is cr...
NSManagedObjectModel// Returns the managed object model for the application.// If the model doesnt already exist, it is cr...
NSManagedObjectModel// Returns the managed object model for the application.// If the model doesnt already exist, it is cr...
NSManagedObjectContextScratch Pad for EntitiesQueried objects are pulled into context  Can be FaultedEntities inserted int...
NSManagedObjectContextNot thread safe!One context per threadMore than one context per coordinator  Merge notificationsConc...
NSManagedObjectContext// Returns the managed object context for the application.// If the context doesnt already exist, it...
NSManagedObjectContext// Returns the managed object context for the application.// If the context doesnt already exist, it...
SavingSave occurs per contextSaves changes to persistent storeShould save on applicationWillTerminate:Can be reset to disc...
Saving- (void)saveContext{    NSError *error = nil;    NSManagedObjectContext *managedObjectContext = self.managedObjectCo...
NSManagedObjectRepresents an entity in your modelSuperclass of managed object subclassesAccess attributes via KVC/KVO and ...
Querying EntitesNSPredicateRich query syntaxAggregate property valuesCompound predicatesQueries can return faulted entitie...
FaultsOnly object IDPerformance & memoryInclude specific propertiesPrefetch relationships
Querying EntitesNSManagedObjectContext *managedObjectContext = [self managedObjectContext];NSFetchRequest *request = [[NSF...
Querying EntitesNSManagedObjectContext *managedObjectContext = [self managedObjectContext];NSFetchRequest *request = [[NSF...
Querying EntitesNSManagedObjectContext *managedObjectContext = [self managedObjectContext];NSFetchRequest *request = [[NSF...
Querying EntitesNSManagedObjectContext *managedObjectContext = [self managedObjectContext];NSFetchRequest *request = [[NSF...
PredicatesNSPredicate *predicate = [NSPredicate predicateWithFormat:@"grade > %d", 7];NSPredicate *testForTrue =  [NSPredi...
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 m...
Inserting Entities- (void)insertNewObject:(id)sender{   NSManagedObjectContext *context = [self.fetchedResultsController m...
Inserting Entities- (void)insertNewObject:(id)sender{   NSManagedObjectContext *context = [self.fetchedResultsController m...
Inserting Entities- (void)insertNewObject:(id)sender{   NSManagedObjectContext *context = [self.fetchedResultsController m...
Deleting Entites Entities are marked as deleted No longer returned in queries Not actually deleted until context is saved ...
Deleting Entites- (void)deleteEvent:(NSManagedObject*)event{   NSManagedObjectContext *managedObjectContext = [self manage...
Updating EntitiesSame as insertChange properties and save contextUpdates can be discarded before save by discardingor rese...
MigrationsSchemas changeCreate new model versionAutomatic lightweight migrationManual migrationNot all changes require mig...
Concurency TypesiOS 5 >=NSConfinementConcurrencyType Pre iOS 5 ConcurrencyNSPrivateQueueConcurrencyType Private dispatch q...
ResourcesCore Data Programming Guidehttp://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProg...
ResourcesMagical Recordhttp://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide....
Q&A
Upcoming SlideShare
Loading in …5
×

Core data orlando i os dev group

626
-1

Published on

Scott Ahten's presentation on Core Data presented to the Orlando iOS group during the January 2013 meetup.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
626
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
28
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Core data orlando i os dev group

  1. 1. INTRODUCTIONTO CORE DATATO CORE DATAOrlando iOS Developer Group01/23/2013 Scott Ahten AHTEN INDUSTRIES
  2. 2. Who Am I?Scott Ahten, Ahten IndustriesTechnologist, iOS Developerscott@ahtenindustries.com
  3. 3. Topics CoveredWhat is Core Data?When should I use Core Data?Framework overviewUsing Core DataMigrationsThreading & concurrency types
  4. 4. What is Core DataNot a Database!Not an Object Relational Mapping framework
  5. 5. What is Core DataObject Persistence FrameworkCRUD operationsQueries using NSPredicate Aggregate queriesMultiple persistent storeAvailable on iOS and Mac OS X Desktop
  6. 6. PersistentStore TypesStore TypesBinaryIn MemoryXML (Desktop Only)SQLiteCustom Types
  7. 7. Core Data vs. SQLite SQLite Core Data Multiple Update YES NO Multiple Delete YES NOAuto Populate Objects NO YES Custom SQL YES NO AutomaticLightweight Migrations NO YES Speed YES YES Model Objects NO YES
  8. 8. When Should IUse CoreData?Use CoreData?Wrong QuestionWhen Shouldn’t I use Core Data?Really Fast - Highly Optimized by AppleAll but trivial and special casesYou should be using Model objects
  9. 9. Core Data and MVC View View Controller Controller Model Model Core Data
  10. 10. Model ObjectsNSManagedObject subclassLifecycle eventsValidationFaultingUndo SupportRelationships
  11. 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. 12. Core Data StackSetup in App DelegateXcode Core Data template
  13. 13. NSPersistentStoreCoordinator Coordinates access to one or more persistent stores Managed Object Model Set store options
  14. 14. NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt already exist, it is created and the applications 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:[selfmanagedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURLoptions:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator;}
  15. 15. NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt already exist, it is created and the applications 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:[selfmanagedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURLoptions:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator;}
  16. 16. NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt already exist, it is created and the applications 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:[selfmanagedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURLoptions:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator;}
  17. 17. NSPersistentStoreCoordinator// Returns the persistent store coordinator for the application.// If the coordinator doesnt already exist, it is created and the applications 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:[selfmanagedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURLoptions:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator;}
  18. 18. NSManagedObjectModel Schema for Models Entities, properties, relationships, etc. Validations Fetch Requests Configurations Objective-C Subclass
  19. 19. NSManagedObjectModel
  20. 20. Attribute Types Integer Types Decimal Double Float String Boolean Date Binary Data
  21. 21. Other Types? Serialize to NSData via NSCoder Value Transformer and Transformable type Opaque to Queries NSManagedObject subclass
  22. 22. Attribute Options Transient Optional Indexed Default Values Store in external record file (iOS 5 >=)
  23. 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. 24. NSManagedObjectModel// Returns the managed object model for the application.// If the model doesnt already exist, it is created from the applications 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. 25. NSManagedObjectModel// Returns the managed object model for the application.// If the model doesnt already exist, it is created from the applications 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. 26. NSManagedObjectModel// Returns the managed object model for the application.// If the model doesnt already exist, it is created from the applications 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. 27. NSManagedObjectContextScratch Pad for EntitiesQueried objects are pulled into context Can be FaultedEntities inserted into contextChanges are not persisted until calling save:
  28. 28. NSManagedObjectContextNot thread safe!One context per threadMore than one context per coordinator Merge notificationsConcurrency Types (iOS 5>=) Blocks, GCD queues
  29. 29. NSManagedObjectContext// Returns the managed object context for the application.// If the context doesnt 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. 30. NSManagedObjectContext// Returns the managed object context for the application.// If the context doesnt 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. 31. SavingSave occurs per contextSaves changes to persistent storeShould save on applicationWillTerminate:Can be reset to discard changes
  32. 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. 33. NSManagedObjectRepresents an entity in your modelSuperclass of managed object subclassesAccess attributes via KVC/KVO and propertiesPass NSManagedObjectIDs between threadsXcode can generate subclass with accessorsCan be a fault
  34. 34. Querying EntitesNSPredicateRich query syntaxAggregate property valuesCompound predicatesQueries can return faulted entities based on resulttypeBatch size
  35. 35. FaultsOnly object IDPerformance & memoryInclude specific propertiesPrefetch relationships
  36. 36. Querying EntitesNSManagedObjectContext *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. 37. Querying EntitesNSManagedObjectContext *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. 38. Querying EntitesNSManagedObjectContext *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. 39. Querying EntitesNSManagedObjectContext *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. 40. PredicatesNSPredicate *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. 41. Inserting Entities Insert into managed object context Entities are not yet persisted until context is saved
  42. 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 thetemplate. [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. 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 thetemplate. [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. 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 thetemplate. [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. 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 thetemplate. [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. 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. 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. 48. Updating EntitiesSame as insertChange properties and save contextUpdates can be discarded before save by discardingor resetting the context
  49. 49. MigrationsSchemas changeCreate new model versionAutomatic lightweight migrationManual migrationNot all changes require migration Validation, default values, Objective-C class
  50. 50. Concurency TypesiOS 5 >=NSConfinementConcurrencyType Pre iOS 5 ConcurrencyNSPrivateQueueConcurrencyType Private dispatch queueNSMainQueueConcurrencyType Main Queue
  51. 51. ResourcesCore Data Programming Guidehttp://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.htmlPredicate Programming Guidehttp://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/predicates.htmlGrand Central Dispatch (GCD)http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
  52. 52. ResourcesMagical Recordhttp://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.htmlMulti-Context Core Datahttp://www.cocoanetics.com/2012/07/multi-context-coredata/Core Data Editorhttp://christian-kienle.de/CoreDataEditor
  53. 53. Q&A
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×