Much Wow.

ADVANCED CORE DATA
The Things You Thought You Could Ignore
WHO I AM
•

Aaron Douglas	


•

Milwaukee, WI USA	


•

Mobile Maker for
Automattic Inc.
(WordPress.com)	


•

Prior life ...
ADVANCED CORE DATA
TOPICS
•

Concurrency	


•

Caching Data	


•

Migrating Schemas	


•

Undo Management	


•

Performanc...
ASK QUESTIONS
This talk is all about you!
CORE DATA IN 30 SECONDS
•

Object Graph Store	


•

Abstracts Persistence	


•

Provides a lot for doing a little	


•

Va...
CONCURRENCY
“It’s so simple!”
MAIN THREAD
•

Easy 	


•

Pretty fast	


•

Xcode wizard template	


•

Good enough for most
apps & prototypes
WHEN DO I WORRY?
👉 Core Data 👎	


•

Stuttering / Instruments

•

Asynchronous operations	


•

Batch processing	


•

Fut...
THREADING CAVEATS
•

NSManagedObjects belong to a single context	


•

Do not share between threads/contexts	


•

Pass by...
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
NSManage...
QUEUES
•

NSManagedObjectContext initWithConcurrencyType:	

•

NSMainQueueConcurrencyType	


•

NSPrivateQueueConcurrencyT...
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 chil...
CHALLENGES

•

Saving 	


•

Merging	


•

Conflicts
SAVING
•

NSManagedObjectContextDidSaveNotification	


•

Save in one spot	


•

Handling problems
MERGING
•

NSMergePolicy	


•

NSErrorMergePolicy - default	


•

NSMergeByPropertyStoreTrumpMergePolicy 	


•

NSMergeByP...
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 & deleteCacheW...
BACKGROUND FETCHING
•

NSPersistentStoreCoordinator	


•

Background fetch to warm up the cache

request.resultType =
NSMa...
MIGRATING
SCHEMAS
VERSIONING
•

Why use it?	


•

Version number - hint	


•

Hashes
ENTITY HASH
•

Name, Inheritance, Persistent properties	


•

Class name, transient properties, user info,
validation pred...
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	
...
App	

Version
1.0

1.1

2.0

3.0

1

1

2

3

Model	

Version
App	

Version
1.0

3.0

Model	

Version
1
3
NSInferMappingModelAutomaticallyOption
INFERRED LIMITATIONS
•

Add & Remove Attributes	


•

Non-optional becomes optional	


•

Optional becomes non-optional wi...
MANUAL MAPPING
•

More complex scenarios	


•

Mapping model is for specific version to version	


•

Multiple version chan...
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	


•

S...
Usage
NSUndoManager *undoManager =
[[NSUndoManager alloc] init];
!

undoManager.levelsOfUndo = 10;
!

context.undoManager ...
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	


•

Op...
PREDICATES
•

contains	


•

endsWith	


•

like	


•

matches	


•

non-text first
MEMORY
•

Autorelease pools	


•

NSManagedObjectContext reset	


•

NSManagedObjectContext
refreshObject:mergeChanges:
QUESTIONS?
REFERENCES
•

Core Data Programming Guide - Apple

This documentation is seriously out of date.

No really.

It’s bad.	


...
THANKS!
Contact Information
Aaron Douglas	

@astralbodies	

http://github.com/astralbodies
Upcoming SlideShare
Loading in …5
×

Advanced Core Data - The Things You Thought You Could Ignore

3,519 views

Published on

So you've been using Core Data in your apps and think it's great and simple and super powerful. But now you're starting to run into problems with your apps that you can't explain and possibly even performance issues. This session will cover some of the more advanced topics about Core Data including doing things in the background (concurrency), caching data, migrating schemas, and dealing with undo management.

Published in: Technology

Advanced Core Data - The Things You Thought You Could Ignore

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

×