Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Multi-Threaded Core Data

1fa9cb8c7997c8c4d3d251fb5e41f749?s=47 Realm
November 26, 2015

Multi-Threaded Core Data

Presented by Marcus Zarra at #Pragma 2015

1fa9cb8c7997c8c4d3d251fb5e41f749?s=128

Realm

November 26, 2015
Tweet

Transcript

  1. Core Data
 Multi-Threading Clarity Marcus S. Zarra

  2. Topics for Discussion • Core concepts for Core Data Threading

    • The old way (still works) • The hard way (please don’t do this) • The “best” way (why we are here) • Guidelines
  3. Why? (Or Why Not?)

  4. Core Concepts • Single Source of Truth • The UI

    Thread holds the truth • Non-user data manipulation should NEVER be on the main thread.
  5. The old way (pre iOS 6) • One NSPersistentStoreCoordinator •

    Every NSManagedObjectContext talked to the PSC • Changes Synced via NSNotification PSC Main
 MOC Child
 MOC Child
 MOC notification notification notification notification notification
  6. Issues • Large amount of code • Threading rules are

    unclear • Surprise thread blocking • Very chatty notifications • Very easy to impact performance • A little better in iOS 9
  7. The “hard” way • SQLite is designed for multi-process access

    • You can have more than one PSC • Each MOC can have its own PSC • One PSC won’t block another • True async processing PSC Main
 MOC Child
 MOC Child
 MOC PSC PSC DB 10% PSC 90%
  8. Issues • HARD!!! • No intra-process communication! • Notifications are

    hard (but not impossible) • Threading can be very tricky • Maintainability just left the room • This is how iCloud works • Can be used with Apple Watch
  9. The “best” way • Best is NOT fastest • Best

    is easiest/most maintainable • NSManagedDocument PSC Main
 MOC Child
 MOC Child
 MOC Private
 MOC
  10. Issues • Slightly slower • Rough for new developers •

    Can be more code • Code puke is easy
  11. Guidelines • Single source of truth • Do not reuse

    child MOCs • Data changes go up, not down or sideways • NSFetchedResultsController WILL block the main thread on a child MOC save • Instruments, Instruments, INSTRUMENTS! Main
 MOC Child
 MOC Main
 MOC Child
 MOC
  12. Thank you Marcus S. Zarra
 marcus@cimgf.com www.cimgf.com @mzarra