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
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
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]);
}
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
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
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