Advanced Core Data - The Things You Thought You Could Ignore
-
Upload
aaron-douglas -
Category
Technology
-
view
1.323 -
download
1
description
Transcript of Advanced Core Data - The Things You Thought You Could Ignore
ADVANCED CORE DATAThe Things You Thought You Could Ignore
Much Wow.
WHO I AM
• Aaron Douglas
• Milwaukee, WI USA
• Mobile Maker for Automattic Inc. (WordPress.com)
• Prior life Enterprise Java
• @astralbodies
ADVANCED CORE DATA TOPICS
• Concurrency
• Caching Data
• Migrating Schemas
• Undo Management
• Performance
ASK QUESTIONSThis talk is all about you!
CORE DATA IN 30 SECONDS
• Object Graph Store
• Abstracts Persistence
• Provides a lot for doing a little
• Validation, faulting, paging, querying, versioning
CONCURRENCY“It’s so simple!”
MAIN THREAD
• Easy
• Pretty fast
• Xcode wizard template
• Good enough for most apps & prototypes
WHEN DO I WORRY?
• Stuttering / Instruments 👉 Core Data 👎
• Asynchronous operations
• Batch processing
• Future-proofing app architecture
THREADING CAVEATS
• NSManagedObjects belong to a single context
• Do not share between threads/contexts
• Pass by NSManagedObjectID
• [[managedObject objectID] isTemporaryID]
IN THE BACKGROUND
• Thread containment
• Queues
• Multiple contexts
• Single persistent store coordinator
THREAD CONTAINMENT
• Each thread gets its own context
• Manually manage contexts
• Merge in changes from NSManagedObjectContextDidSaveNotification
QUEUES• NSManagedObjectContext initWithConcurrencyType:
• NSMainQueueConcurrencyType
• NSPrivateQueueConcurrencyType
• NSConfinementConcurrencyType
• Parent context
• NSManagedObjectContextDidSaveNotification
QUEUES
• performBlock - immediately returns
• performWithBlockAndWait
• Main thread can still execute directly
PREFERRED SETUP
• Primary: Private Queue
• UI: Main Queue as child of Primary
• Background: Private Queue as child of Primary
• Allows for asynchronous saves
http://floriankugler.com/blog/2013/4/2/the-concurrent-core-data-stack
CHALLENGES
• Saving
• Merging
• Conflicts
SAVING
• NSManagedObjectContextDidSaveNotification
• Save in one spot
• Handling problems
MERGING• NSMergePolicy
• NSErrorMergePolicy - default
• NSMergeByPropertyStoreTrumpMergePolicy
• NSMergeByPropertyObjectTrumpMergePolicy
• NSOverwriteMergePolicy
CONFLICTS
• NSErrorMergePolicy
• NSError userInfo[@“conflictList”]
• User probably needs to decide
• UX is key!
CACHING DATA
FETCHED RESULTS CONTROLLER
• NSFetchedResultsController
• Listens for context changes
• Cache name & deleteCacheWithName:
BACKGROUND FETCHING
• NSPersistentStoreCoordinator
• Background fetch to warm up the cacherequest.resultType = NSManagedObjectIDResultType
• Full fetch on background thread - NSPersistentStoreCoordinator caching
MIGRATING SCHEMAS
VERSIONING
• Why use it?
• Version number - hint
• Hashes
ENTITY HASH
• Name, Inheritance, Persistent properties
• Class name, transient properties, user info, validation predicates, default values
• Hash modifier
AUTOMATIC MIGRATION
• Infer Mapping Model
• Migrate Store Automatically
LIGHTWEIGHT MIGRATION
• SQLite - all internal to db & no objects loaded into memory
• Speedy
• Light on memory
HEAVYWEIGHT MIGRATION
• Every object loaded into memory
• Manually map and manipulate data
INFER MAPPING MODEL
• Not a silver bullet
• Model upgrades can skip versions
• Does not merge multiple versions
• Business logic between upgrades is lost
App Version
Model Version
1.0
1
1.1
1
2.0
2
3.0
3
App Version
Model Version
1.0
1
3.0
3NSInferMappingModelAutomaticallyOption
INFERRED LIMITATIONS
• Add & Remove Attributes
• Non-optional becomes optional
• Optional becomes non-optional with default
• Renaming entity or property
MANUAL MAPPING
• More complex scenarios
• Mapping model is for specific version to version
• Multiple version change not support unless sequential migrations used
• Code is needed for sequential migrations
TESTING
• Test migrations LIKE CRAZY
• Unit tests can help here!
• Don’t assume current version only
UNDO MANAGEMENT
UNDO MANAGEMENT
• NSUndoManager
• Built-in support in NSManagedObjectContext
• Undo manager is nil in iOS
• Simple to use, easy to mess up
Usage
NSUndoManager *undoManager = [[NSUndoManager alloc] init]; !undoManager.levelsOfUndo = 10; !context.undoManager = undoManager; !... ![context.undoManager undo];
PERFORMANCE
INSTRUMENTS• Run on the device
• Fetches
• Saves
• Faults
• Cache Misses
LOGGING
• -com.apple.CoreData.SQLDebug 1
• Higher the number = more info
• Loses usefulness pretty quick
• Open SQLite file directly - Base.app
PREDICATES• contains
• endsWith
• like
• matches
• non-text first
MEMORY
• Autorelease pools
• NSManagedObjectContext reset
• NSManagedObjectContext refreshObject:mergeChanges:
QUESTIONS?
REFERENCES
• Core Data Programming Guide - AppleThis documentation is seriously out of date.No really.It’s bad.
• Core Data 2nd Ed - Marcus Zarra
THANKS!
Contact Information
Aaron Douglas
@astralbodies
http://github.com/astralbodies