Your SlideShare is downloading. ×
  • Like

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Core Data presentation

  • 4,149 views
Published

Core Data presentation by Darren Stockes to the Houston iPhone Development meetup on October 26 2010.

Core Data presentation by Darren Stockes to the Houston iPhone Development meetup on October 26 2010.

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
4,149
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
156
Comments
0
Likes
6

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide





  • No bulk operations
    - no capability for “delete where x = y”, each object must be retrieved and deleted
    - no sum, avg, etc
    Object population
    - core data removes the need for “plumbing code” to populate objects and save changes to them back
    Custom sql
    - most persistence frameworks take some of the sql out of the hands of developers. core data does this more than most
    Select only certain fields
    - you might want to only retrieve a field or two out of maybe 10, this isn’t possible in core data
    - faulting is only a partial solution (to be discussed when we get to querying objects)
    Automated Migrations
    - core data provides some default migration capability
    - there is a framework for developing quite complex migrations over multiple versions
    Less Code
    - related to automatic object population
    - you will write a lot less code not only for plumbing, but for fault type situations as well
    - SQLite api is a little complicated
  • NSPersistentStore encapsulates the actual storage format for the core data store

    NSPersistentStoreCoordinator encapsulates the managed object model sitting on top of that storage format

    NSManagedObjectContext is our interface to query and change objects











  • a hash value is stored with each version of a versioned core data store

    automatic migrations represent a situation where there is a mapping model found that matches the user’s current hash and the desired target version

    manual migration represent the opposite case - there is no mapping model found that matches the user’s current hash version and the desired target version
    - desktop stores created in Tiger will have this issue

    Progressive migrations are a special case of manual migrations where an intermediate mapping model is used before the final migration can take place to the bring the model to the desired target version


  • After adding this code to the beginning of the persistentStoreCoordinator, create a desktop console app and use the same model to generate code and create a .sqlite db

    The sqlite file should be added to your xcode project under resources





Transcript

  • 1. Using Core Data on iOS Houston iPhone Developer Meetup October 26, 2010
  • 2. Who Am I? • Darren Stokes, Concurrent Access Software • Consultant and Indie Developer • darrenstokes@me.com • @darrenstokes • http://blog.darrenstokes.com
  • 3. What is Core Data? • Available both on the desktop (>= Tiger)and on the iPhone OS starting with 3.0 • Allows definition of Managed Objects • Functionality to create, update, delete, query • Multiple back-end storage options
  • 4. Is it an ORM? • Sort of... • Does not support mapping to an existing store. • More like Active Record • Similar to generating the database structure from Hibernate mapping files • You don’t define the sequence/identity primary keys, only relationships (but they are still there) • -(NSManagedObjectID *) objectID
  • 5. Storage Options • Binary • In-memory • XML • Not available on the iPhone • SQLite • Only option that does not require the entire store to reside in memory
  • 6. Core Data vs. SQLite SQLite Core Data Bulk/Set Yes No Operations Automatic object No Yes population Custom SQL Yes No Select only certain Yes No fields Automated No Yes Migrations Less Complex No Yes Code
  • 7. Interface to Core Data NSManagedObjectContext NSPersistentStoreCoordinator NSPersistentStore
  • 8. NSPersistentStoreCoordinator - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator != nil) { return persistentStoreCoordinator; } NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"ReadingLog.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; }
  • 9. NSManagedObjectModel - (NSManagedObjectModel *)managedObjectModel { if (managedObjectModel != nil) { return managedObjectModel; } managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; return managedObjectModel; }
  • 10. Model Demo
  • 11. NSManagedObjectContext - (NSManagedObjectContext *) managedObjectContext { if (managedObjectContext != nil) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator: coordinator]; } return managedObjectContext; }
  • 12. Querying for Objects NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"LogEntry" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"readingMaterial.name" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; NSPredicate *predicate = nil; predicate = [NSPredicate predicateWithFormat:@"user.name = %@", user.name]; [fetchRequest setPredicate:predicate]; NSError *error = nil; NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
  • 13. Faulted Objects • NSFetchRequest • Only ObjectId • setResultType:NSManagedObjectIDResultType • Faulted Object (no props, only ObjectId) • setIncludesPropertyValues:NO • Default is Properties populated with no relationships • Pre-fetch relationships • setRelationshipKeyPathsForPrefeching:NSArray (array of NSString objects)
  • 14. Deleting an Object User *user = [fetchedResultsController objectAtIndexPath:indexPath]; [managedObjectContext deleteObject:user]; NSError *error; if (![managedObjectContext save:&error]) { NSLog(@"Failed to save to data store: ?", [error localizedDescription]); NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey]; if(detailedErrors != nil && [detailedErrors count] > 0) { for(NSError* detailedError in detailedErrors) { NSLog(@" DetailedError: ?", [detailedError userInfo]); } } else { NSLog(@" ?", [error userInfo]); } }
  • 15. Inserting an Object if (user == nil) { NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext]; user = [[User alloc] initWithEntity:entity insertIntoManagedObjectContext:managedObjectContext]; } [nameField endEditing:YES]; user.name = nameField.text; NSError *error = nil; if (![managedObjectContext save:&error]) { NSLog(@"Failed to save to data store: ?", [error localizedDescription]); NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey]; if(detailedErrors != nil && [detailedErrors count] > 0) { for(NSError* detailedError in detailedErrors) { NSLog(@" DetailedError: ?", [detailedError userInfo]); } } else { NSLog(@" ?", [error userInfo]); } }
  • 16. Updating an Object • Same as insert • Make changes followed by ManagedObjectContext save
  • 17. NSFetchedDataController • Only available on the iPhone • Provides an easy way to integrate UITableView instances with Core Data results • Retrieves faulted objects • Can take care of updates required to the table view as a result of individual object updates (NSFetchedResultsControllerDelegate) • Be careful with the cache
  • 18. Code Demo
  • 19. Migrations • Core Data Model Versioning and Data Migration Programming Guide • Good blog post • http://iphonedevelopment.blogspot.com/ 2009/09/core-data-migration- problems.html • Automatic vs. Manual vs. Progressive Migrations • Changes to Entity Name,Validation predicate, and default values do not trigger a migration
  • 20. Code Demo
  • 21. Tip: Table Updates 3.0.x vs. 3.1.x • Table update due to inserted object needs different code in 3.0.x vs. 3.1.x • See code in TableViewBase.m in sample
  • 22. Tip: Providing Default Data NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *docFolder = [self applicationDocumentsDirectory]; if (![fileManager fileExistsAtPath:docFolder]) { [fileManager createDirectoryAtPath:docFolder attributes:nil]; } NSString *filePath = nil; filePath = [docFolder stringByAppendingPathComponent:@"ReadingLog.sqlite"]; if (![fileManager fileExistsAtPath:filePath]) { NSString *defaultDB = [[NSBundle mainBundle] pathForResource:@"ReadingLog" ofType:@"sqlite"]; NSError *error = nil; if (![[NSFileManager defaultManager] copyItemAtPath:defaultDB toPath:filePath error:&error]) { NSLog(@"%@:%s Error copying file %@", [self class], _cmd, error); } }
  • 23. Threading • Must create a new NSManagedObjectContext for each thread • NSManagedObjects are associated with a particular context • NSManagedObjectContext can be updated with changes from other contexts
  • 24. Code Demo
  • 25. Core Data Ecosystem • ZSync • Core Data sync on iphone and desktop • http://www.zarrastudios.com/ZSync/ ZSync.html • mogenerator • Does more interesting core data class generation • http://rentzsch.github.com/mogenerator/ • Base • SQLite database editor
  • 26. Core Data Resources • Core Data Documentation • Core Data Book (Zarra) - PragProg.com • More iPhone 3 Development (Mark and LaMarche) - Apress • MDN Podcast #10 • Zarra’s blog (Cocoa is my Girlfriend)
  • 27. Q &A