Adventures in Multithreaded Core Data

Inferis
InferisSoftware Architect, Self-employed at Home Office
Adventures in
Multithreaded Core Data
    CocoaheadsBE - Zoersel, 2012-09-24
Introduction
Adventures in Multithreaded Core Data
Tom Adriaenssen
I love...
‣ ... my wife
‣ ... my 4 kids
‣ ... to code
‣ ... to play a game of squash
‣ ... good beer
I open sourced...
... some code:

‣ IIViewDeckController: “An
  implementation of the
  sliding functionality found in
  the Path 2.0 or Facebook
  iOS apps.”

‣ IIDateExtensions

‣ IIPopoverStatusItem

See: http://github.com/inferis
I made...
... some apps:




         Butane                     Drash
     http://getbutane.com          http://dra.sh

         Hi, @10to1!
Butane
                        Campfire client for iOS

‣ Official Campfire client
  kinda sucks, so we
  rolled our own

‣ Somewhat concurrent
  app

‣ Uses Core Data

‣ Together with 10to1
This presentation is about
      what I learned
  while coding Butane.
Agenda
Agenda

‣ Core Data Primer
‣ MagicalRecord
‣ Concurrency problems
‣ Concurrency solutions
Core Data Primer
What is: Core Data?
                ‣ Per the documentation:
                ‣ The  Core  Data  framework  provides  
                  generalized  and  automated  solutions  
                  to  common  tasks  associated  with  
                  object  life-­‐cycle  and  object  graph  
                  management,  including  persistence.




http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdTechnologyOverview.html#//apple_ref/doc/uid/TP40009296-SW1
Wait, what?
What isn’t: Core Data?

‣ It’s not an RDBMS.
‣ If you want a database and SQL, use
  Sqlite:
What isn’t: Core Data?

‣ It’s not just an ORM (Object Relational
  Mapper)
‣ It may look like there’s SQL under the
  hood, but that’s not necessarily the case.
So, what is it then?
Core Data provides:
‣ persistence
‣ change tracking
‣ relations (object graph)
‣ lazy loading (“faulting”)
‣ validation
‣ works well with Cocoa (KVO, KVC)
Basically:

‣ A system to store data
‣ Persistence agnostic (local storage,
  iCloud, AFIncrementalStore, ...)
‣ No need to write SQL to query
‣ You can keep to Objective-C
Your tools:
‣ NSPersistentStore
‣ NSManagedObjectContext
‣ NSManagedObject
‣ NSManagedObjectID  
‣   NSFetchRequest
‣   NSEntityDescription
‣   NSPredicate
‣   NSSortDescription
A picture says a 1000 words...
MagicalRecord
MagicalRecord
           ‣ Writing Core Data code is tedious.
           ‣ You need quite a bit of boilerplate code
             to do something simple:

NSManagedObjectContext  *moc  =  [self  managedObjectContext];
NSEntityDescription  *entityDescription  =  [NSEntityDescription  entityForName:@"Employee"  inManagedObjectContext:moc];
NSFetchRequest  *request  =  [NSFetchRequest  new];
[request  setEntity:entityDescription];
  
NSSortDescriptor  *sortDescriptor  =  [[NSSortDescriptor  alloc]  initWithKey:@"firstName"  ascending:YES];
[request  setSortDescriptors:@[sortDescriptor]];
  
NSError  *error;
NSArray  *array  =  [moc  executeFetchRequest:request  error:&error];

if  (array)
{
           //  display  items  (eg  in  table  view)
}
else  {
        //  Deal  with  error...
}
MagicalRecord
‣ MagicalRecord tries to solve this.


‣ = ActiveRecord pattern for Core Data.
‣ Encapsulates the tediousness of plain
  Core Data code.
MagicalRecord
           ‣ Writing MagicalRecord enable code is
             tedious no more:
           ‣ That same example is now this:


NSManagedObjectContext  *moc  =  [self  managedObjectContext];
NSArray  *array  =  [Employee  MR_findAllSortedBy:@"firstname"  ascending:YES  inContext:context];

if  (array)
{
           //  display  items  (eg  in  table  view)
}
else  {
        //  Deal  with  error...
}
Adventures in Multithreaded Core Data
Great, isn’t it?
MagicalRecord
+ write less code
+ your code becomes more readable
+ good for apps requiring simple storage scenarios (=most
  apps, probably)
+ hides complexity
-   hides complexity
-   easy to start, but diving deeper becomes harder
- uses defaults that are suboptimal in a multithreaded app
- concurrency errors and issues are subtle
MagicalRecord
‣      used MagicalRecord from the start
‣ Took me a while to find out the problems
  I was having were related to the
  complexity hiding
‣ The defaults are okay only for so much
  app complexity
MagicalRecord
‣ That said: Magical Record is great.
‣ It will speed up your Core Data
  development by several factors.
‣ Also: take a look at mogenerator:
 ‣   http://rentzsch.github.com/mogenerator/

 ‣   or: brew  install  mogenerator
MagicalRecord

‣ So I threw it out.
MagicalRecord

‣ So I threw it out.
‣ But not completely.
MagicalRecord

‣ So I threw it out.
‣ But not completely.
‣ More about that later.
The problems described hereafter only apply
to the persistent stores with external backing
             (for example: sqlite).
Concurrency: problems
Problems?
Problems?

‣ Core Data Objects are not thread safe.
Problems?

‣ Core Data Objects are not thread safe.
‣ In essence: you can’t share them across
  threads (except for NSManagedObjectID).
Problems?

‣ Core Data Objects are not thread safe.
‣ In essence: you can’t share them across
  threads (except for NSManagedObjectID).
‣ Core Data locks objects, even for read
  operations.
Object storage is locked
for read operations, too
‣ Objects used to power the UI must be
  fetched on the UI thread.
‣ Heavy/complex fetch requests (queries)
  block the UI thread while fetching the
  objects. You don’t want that.
Objects aren’t supposed to
be shared between threads
‣ The NSManagedObjectContext “locks” an
  object when you read one of its properties.
‣ This can cause a deadlock when you do
  access the same data from 2 threads.
‣ Reason: faulting support can change the
  object even while just reading from it.
‣ You can’t turn it off.
Adventures in Multithreaded Core Data
Luckily, we can fix or workaround these
               problems.
Concurrency: solutions
Keep to your thread
Keep to your thread


‣ pre-iOS5: use thread confinement
Keep to your thread


‣ pre-iOS5: use thread confinement
‣ iOS5 and later: use nested contexts
Thread confinement
‣ In essence: keep an NSManagedObjectContext per
  thread
‣ Be very careful when going from one thread to
  another.


‣ MagicalRecord tries to hide this from you:
  ‣ It automatically provides a context for each thread
  ‣ This is a bit counterintuitive since you start mixing
    objects across threads quite easily.
Thread confinement




     Image source: Cocoanetics
Nested contexts
‣   Introduced in iOS5
‣   Uses Grand Central Dispatch and dispatch queues
‣   Core Data manages threading for you
‣   Better than thread confinement
    ‣   more straightforward
    ‣   more flexible


‣   MagicalRecord hides this from you, too.
    ‣   Automatically switches to dispatch queues on iOS5 even
        though the API remains the same.
Nested contexts




    Image source: Cocoanetics
Nested contexts
‣ NSManagedObjectContext = cheap
‣ You can nest contexts
‣ Each context has its private dispatch
  queue
‣ No manual thread synchronization
  necessary
Queue types
    ‣ NSConfinementConcurrencyType
        ‣     The old way (thread confinement)

    ‣ NSPrivateQueueConcurrencyType
        ‣     The context has its own private dispatch queue

    ‣ NSMainQueueConcurrencyType
        ‣     The context is associated with the main queue (or runloop, or UI
              thread)


parentMoc  =  [[NSManagedObjectContext  alloc]  initWithConcurrencyType:NSMainQueueConcurrencyType];
[parentMoc  setPersistentStoreCoordinator:coordinator];

moc  =  [[NSManagedObjectContext  alloc]  initWithConcurrencyType:NSPrivateQueueConcurrencyType];
moc.parentContext  =  parentMoc;
Thread safe?
   ‣ performBlock:   
     performBlockAndWait:
   ‣ Run a block you provide on the queue
     associated with the context.
        ‣ Object access in the block is thread safe
[context  performBlockAndWait:^{
        for  (Room*  room  in  [Room  findAllInContext:context])  {
                room.joinedUsers  =  [NSSet  set];
                room.knowsAboutJoinedUsersValue  =  NO;
                room.unreadCountValue  =  0;
                room.status  =  @"";
        }
        NSError*  error  =  nil;
        [context  save:&error];
}];
performBlock, and wait
-­‐  (void)performBlock:(void  (^)())block;
   ‣   executes the block on the context dispatch queue as soon as possible

   ‣   nonblocking call

   ‣   code will not execute immediately



-­‐  (void)performBlockAndWait:(void  (^)())block;
   ‣   executes the block on the context dispatch queue immediately

   ‣   blocks the current execution until block is done

   ‣   can cause a deadlock (if you’re already running code on the same
       queue)
When to use what?
‣   performBlock:
    ‣   For actions which are “on their own”
    ‣   Consider the code in the block a Unit Of Work
    ‣   Best for save operations
    ‣   Useful for long fetches (use callbacks)


‣   performBlockAndWait:
    ‣   When you need stuff immediately
    ‣   Good for small fetches or “standalone” saves
How is this better than
 thread confinement?
‣ No manual thread handling, Core Data
  handles it for you.
‣ More flexible: as long as you access
  managed objects in the correct context
  using performBlock: you’re pretty safe
 ‣ also applies to the main/UI thread! (unless
   you’re sure you’re on the main thread)
Saving nested contexts
‣ Saves are only persisted one level deep.
‣ Parent contexts don’t pull changes from
  child contexts.
‣ Child contexts don’t see changes by
  parent contexts.
 ‣   Make them plenty and short-lived
How to nest contexts

‣ 2 approaches:
 ‣ root context = NSMainQueueConcurrencyType
 ‣ root context = NSPrivateQueueConcurrencyType
Root = Main
                              ‣ Many child contents
                                with private queues

                              ‣ Root context on main
                                queue

                              ‣ Actual persistence
                                happens on main
                                queue, could block the
                                UI

  Image source: Cocoanetics
Root = Private
                         ‣ Root context with private
                           queue

                         ‣ Many child contents with
                           private queues

                         ‣ context on main queue is
                           child of root

                         ‣ Actual persistence
                           happens in background
                           (does not block the UI)

   Image source: Cocoanetics
What problems did we
    have again?
What problems did we
    have again?

‣ No sharing of NSManagedObjects
  between threads.
What problems did we
     have again?

‣ No sharing of NSManagedObjects
  between threads.
‣ Context locking
Sharing: solution
‣ Pass only NSManagedObjectIDs to
  other threads, not objects.
‣ Refetch the object on a different thread
  or queue to work with it.
‣ Don’t forget to save the ‘original’ object
  first before working with it on the second
  thread or queue.
Complex queries
‣   Use the same technique for complex or large queries.
    1. do the heavy lifting in the background
    2. pass list of NSManagedObjectIDs to another thread
       (e.g. UI thread).
    3. load objects as faults, and let Core Data fault them in
       when you need them (e.g. when accessing a property)


‣   That’s lot of requests, but this is actually more performant
    and desirable in most cases.
Locking: solution
‣ Use child contexts with their own
  dispatch queues.
‣ Use: performBlock: and
  performBlockAndWait:  carefully.
‣ Deadlocks still possible, especially with
  performBlockAndWait:
A word about
 NSManagedObjectIDs
‣ Two types of IDs:
 ‣ temporary
   ‣ when the object hasn’t been persisted to a
     store

 ‣ permanent
   ‣ when the object has been persisted to a
     store
A word about
 NSManagedObjectIDs
‣ Subtle bug: temporary IDs from a non-root
  context don’t get updated to permanent
  IDs when saving in the root context
‣ The object is saved just fine, but the ID is
  not updated correctly.
‣ When passing these around to other
  contexts after saving: you won’t find the
  object in another child context!
A word about
 NSManagedObjectIDs

‣ To the rescue:
  -­‐  (BOOL)obtainPermanentIDsForObjects:
  (NSArray  *)objects  error:(NSError  
  **)error;
A word about
  NSManagedObjectIDs
   -­‐  (BOOL)obtainPermanentIDsForObjects:(NSArray  
   *)objects  error:(NSError  **)error;



‣ Transforms objects with temporary IDs to permanent IDs
  (through the persistent store of the root context).
‣ Do this when creating a managed object and you’re
  safe.
‣ Obtaining permanentIDs is batched, so the performance
  hit is not that high
MagicalRecord
‣ I still use MagicalRecord:
 ‣ Reduced form: no more “automatic”
   context handling --> dangerous!
 ‣ Added some extra sauce to work with
   the nested contexts.
 ‣ The methods MR supplies still allow for
   a speedup when coding.
Useful References


‣   Nested context release notes: http://developer.apple.com/library/mac/#releasenotes/
    DataManagement/RN-CoreData/_index.html
‣   Magical Record: https://github.com/magicalpanda/MagicalRecord
‣   Mogenerator: http://rentzsch.github.com/mogenerator/
‣   A good read on Cocoanetics: http://www.cocoanetics.com/2012/07/multi-context-coredata/
‣   Core data programming guide: http://developer.apple.com/library/mac/#documentation/
    cocoa/Conceptual/CoreData/cdProgrammingGuide.html
‣   Butane: http://getbutane.com
Thanks for listening.


Questions? Contact me:

Twitter: @inferis
App.Net: @inferis
E-mail: tom@interfaceimplementation.be
vCard: http://inferis.org
1 of 73

Recommended

High Performance Core Data by
High Performance Core DataHigh Performance Core Data
High Performance Core DataMatthew Morey
5K views139 slides
Multi-threaded CoreData Done Right by
Multi-threaded CoreData Done RightMulti-threaded CoreData Done Right
Multi-threaded CoreData Done Rightmorrowa_de
1.4K views63 slides
Core Data with multiple managed object contexts by
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contextsMatthew Morey
33.8K views54 slides
Create a Core Data Observer in 10mins by
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10minszmcartor
4K views11 slides
NoSQL and JavaScript: a Love Story by
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
9.3K views36 slides
Bonjour, iCloud by
Bonjour, iCloudBonjour, iCloud
Bonjour, iCloudChris Adamson
2.4K views54 slides

More Related Content

What's hot

Beginning icloud development - Cesare Rocchi - WhyMCA by
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
1.7K views129 slides
Scalable network applications, event-driven - Node JS by
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
1.2K views16 slides
Polyglot persistence with Spring Data by
Polyglot persistence with Spring DataPolyglot persistence with Spring Data
Polyglot persistence with Spring DataCorneil du Plessis
1.2K views25 slides
Getting Started with Datatsax .Net Driver by
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverDataStax Academy
465 views38 slides
Mongo performance tuning: tips and tricks by
Mongo performance tuning: tips and tricksMongo performance tuning: tips and tricks
Mongo performance tuning: tips and tricksVladimir Malyk
6.5K views18 slides
Modern Android app library stack by
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
584 views64 slides

What's hot(20)

Beginning icloud development - Cesare Rocchi - WhyMCA by Whymca
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
Whymca1.7K views
Scalable network applications, event-driven - Node JS by Cosmin Mereuta
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
Cosmin Mereuta1.2K views
Getting Started with Datatsax .Net Driver by DataStax Academy
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
DataStax Academy465 views
Mongo performance tuning: tips and tricks by Vladimir Malyk
Mongo performance tuning: tips and tricksMongo performance tuning: tips and tricks
Mongo performance tuning: tips and tricks
Vladimir Malyk6.5K views
Modern Android app library stack by Tomáš Kypta
Modern Android app library stackModern Android app library stack
Modern Android app library stack
Tomáš Kypta584 views
MongoDB: tips, trick and hacks by Scott Hernandez
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacks
Scott Hernandez5.2K views
Getting started with node JS by Hamdi Hmidi
Getting started with node JSGetting started with node JS
Getting started with node JS
Hamdi Hmidi528 views
Hazelcast by oztalip
HazelcastHazelcast
Hazelcast
oztalip11K views
Nuvola: a tale of migration to AWS by Matteo Moretti
Nuvola: a tale of migration to AWSNuvola: a tale of migration to AWS
Nuvola: a tale of migration to AWS
Matteo Moretti1.1K views
Whats New for WPF in .NET 4.5 by Rainer Stropek
Whats New for WPF in .NET 4.5Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5
Rainer Stropek741 views
Java. Explicit and Implicit Wait. Testing Ajax Applications by Марія Русин
Java. Explicit and Implicit Wait. Testing Ajax ApplicationsJava. Explicit and Implicit Wait. Testing Ajax Applications
Java. Explicit and Implicit Wait. Testing Ajax Applications
MongoDB Performance Tuning and Monitoring by MongoDB
MongoDB Performance Tuning and MonitoringMongoDB Performance Tuning and Monitoring
MongoDB Performance Tuning and Monitoring
MongoDB12.5K views
Birhanu distributive assignment by university
Birhanu distributive assignmentBirhanu distributive assignment
Birhanu distributive assignment
university168 views
Getting started with Elasticsearch and .NET by Tomas Jansson
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
Tomas Jansson35.7K views
Zend framework 03 - singleton factory data mapper caching logging by Tricode (part of Dept)
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging

Similar to Adventures in Multithreaded Core Data

Connecting to a REST API in iOS by
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOSgillygize
27.1K views21 slides
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0 by
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0Cyber Security Alliance
4K views51 slides
The Theory Of The Dom by
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
2.7K views66 slides
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver... by
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...smn-automate
3.6K views57 slides
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant? by
Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?Dmitri Shiryaev
1.8K views54 slides
Performance and Memory Tuning - Part II - Transcript.pdf by
Performance and Memory Tuning - Part II - Transcript.pdfPerformance and Memory Tuning - Part II - Transcript.pdf
Performance and Memory Tuning - Part II - Transcript.pdfShaiAlmog1
295 views10 slides

Similar to Adventures in Multithreaded Core Data(20)

Connecting to a REST API in iOS by gillygize
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
gillygize27.1K views
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0 by Cyber Security Alliance
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
The Theory Of The Dom by kaven yan
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan2.7K views
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver... by smn-automate
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
smn-automate3.6K views
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant? by Dmitri Shiryaev
Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
Dmitri Shiryaev1.8K views
Performance and Memory Tuning - Part II - Transcript.pdf by ShaiAlmog1
Performance and Memory Tuning - Part II - Transcript.pdfPerformance and Memory Tuning - Part II - Transcript.pdf
Performance and Memory Tuning - Part II - Transcript.pdf
ShaiAlmog1295 views
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries by Simon Willison
Jazz up your JavaScript: Unobtrusive scripting with JavaScript librariesJazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Simon Willison48.2K views
Vcenter Server Case Study by Sharon Lee
Vcenter Server Case StudyVcenter Server Case Study
Vcenter Server Case Study
Sharon Lee3 views
Complex Made Simple: Sleep Better with TorqueBox by bobmcwhirter
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
bobmcwhirter1.7K views
Practical Use of MongoDB for Node.js by async_io
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
async_io19.9K views
Intro to IndexedDB (Beta) by Mike West
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)
Mike West2.7K views
Buildingsocialanalyticstoolwithmongodb by MongoDB APAC
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
MongoDB APAC297 views
node.js: Javascript's in your backend by David Padbury
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
David Padbury12.6K views
XPages Blast - ILUG 2010 by Tim Clark
XPages Blast - ILUG 2010XPages Blast - ILUG 2010
XPages Blast - ILUG 2010
Tim Clark2.1K views
Advanced Node.JS Meetup by LINAGORA
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
LINAGORA2K views
Backbone/Marionette introduction by matt-briggs
Backbone/Marionette introductionBackbone/Marionette introduction
Backbone/Marionette introduction
matt-briggs4.6K views

More from Inferis

Practical auto layout by
Practical auto layoutPractical auto layout
Practical auto layoutInferis
1.9K views49 slides
Communicating with GIFs by
Communicating with GIFsCommunicating with GIFs
Communicating with GIFsInferis
1.6K views57 slides
Autolayout primer by
Autolayout primerAutolayout primer
Autolayout primerInferis
2.4K views48 slides
Objective c runtime by
Objective c runtimeObjective c runtime
Objective c runtimeInferis
5.6K views51 slides
I Am A Switcher by
I Am A SwitcherI Am A Switcher
I Am A SwitcherInferis
4.3K views82 slides
Dynamic Silverlight by
Dynamic SilverlightDynamic Silverlight
Dynamic SilverlightInferis
445 views11 slides

More from Inferis(6)

Practical auto layout by Inferis
Practical auto layoutPractical auto layout
Practical auto layout
Inferis1.9K views
Communicating with GIFs by Inferis
Communicating with GIFsCommunicating with GIFs
Communicating with GIFs
Inferis1.6K views
Autolayout primer by Inferis
Autolayout primerAutolayout primer
Autolayout primer
Inferis2.4K views
Objective c runtime by Inferis
Objective c runtimeObjective c runtime
Objective c runtime
Inferis5.6K views
I Am A Switcher by Inferis
I Am A SwitcherI Am A Switcher
I Am A Switcher
Inferis4.3K views
Dynamic Silverlight by Inferis
Dynamic SilverlightDynamic Silverlight
Dynamic Silverlight
Inferis445 views

Recently uploaded

Data-centric AI and the convergence of data and model engineering: opportunit... by
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...Paolo Missier
29 views40 slides
Uni Systems for Power Platform.pptx by
Uni Systems for Power Platform.pptxUni Systems for Power Platform.pptx
Uni Systems for Power Platform.pptxUni Systems S.M.S.A.
38 views21 slides
The details of description: Techniques, tips, and tangents on alternative tex... by
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...BookNet Canada
110 views24 slides
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
66 views25 slides
The Importance of Cybersecurity for Digital Transformation by
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital TransformationNUS-ISS
25 views26 slides
Black and White Modern Science Presentation.pptx by
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptxmaryamkhalid2916
14 views21 slides

Recently uploaded(20)

Data-centric AI and the convergence of data and model engineering: opportunit... by Paolo Missier
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...
Paolo Missier29 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada110 views
The Importance of Cybersecurity for Digital Transformation by NUS-ISS
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital Transformation
NUS-ISS25 views
Black and White Modern Science Presentation.pptx by maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291614 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb12 views
.conf Go 2023 - Data analysis as a routine by Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk90 views
Future of Learning - Khoong Chan Meng by NUS-ISS
Future of Learning - Khoong Chan MengFuture of Learning - Khoong Chan Meng
Future of Learning - Khoong Chan Meng
NUS-ISS31 views
Empathic Computing: Delivering the Potential of the Metaverse by Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst449 views
Spesifikasi Lengkap ASUS Vivobook Go 14 by Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab11 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex19 views
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software91 views
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen... by NUS-ISS
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
NUS-ISS23 views
AI: mind, matter, meaning, metaphors, being, becoming, life values by Twain Liu 刘秋艳
AI: mind, matter, meaning, metaphors, being, becoming, life valuesAI: mind, matter, meaning, metaphors, being, becoming, life values
AI: mind, matter, meaning, metaphors, being, becoming, life values

Adventures in Multithreaded Core Data

  • 1. Adventures in Multithreaded Core Data CocoaheadsBE - Zoersel, 2012-09-24
  • 5. I love... ‣ ... my wife ‣ ... my 4 kids ‣ ... to code ‣ ... to play a game of squash ‣ ... good beer
  • 6. I open sourced... ... some code: ‣ IIViewDeckController: “An implementation of the sliding functionality found in the Path 2.0 or Facebook iOS apps.” ‣ IIDateExtensions ‣ IIPopoverStatusItem See: http://github.com/inferis
  • 7. I made... ... some apps: Butane Drash http://getbutane.com http://dra.sh Hi, @10to1!
  • 8. Butane Campfire client for iOS ‣ Official Campfire client kinda sucks, so we rolled our own ‣ Somewhat concurrent app ‣ Uses Core Data ‣ Together with 10to1
  • 9. This presentation is about what I learned while coding Butane.
  • 11. Agenda ‣ Core Data Primer ‣ MagicalRecord ‣ Concurrency problems ‣ Concurrency solutions
  • 13. What is: Core Data? ‣ Per the documentation: ‣ The  Core  Data  framework  provides   generalized  and  automated  solutions   to  common  tasks  associated  with   object  life-­‐cycle  and  object  graph   management,  including  persistence. http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdTechnologyOverview.html#//apple_ref/doc/uid/TP40009296-SW1
  • 15. What isn’t: Core Data? ‣ It’s not an RDBMS. ‣ If you want a database and SQL, use Sqlite:
  • 16. What isn’t: Core Data? ‣ It’s not just an ORM (Object Relational Mapper) ‣ It may look like there’s SQL under the hood, but that’s not necessarily the case.
  • 17. So, what is it then? Core Data provides: ‣ persistence ‣ change tracking ‣ relations (object graph) ‣ lazy loading (“faulting”) ‣ validation ‣ works well with Cocoa (KVO, KVC)
  • 18. Basically: ‣ A system to store data ‣ Persistence agnostic (local storage, iCloud, AFIncrementalStore, ...) ‣ No need to write SQL to query ‣ You can keep to Objective-C
  • 19. Your tools: ‣ NSPersistentStore ‣ NSManagedObjectContext ‣ NSManagedObject ‣ NSManagedObjectID   ‣ NSFetchRequest ‣ NSEntityDescription ‣ NSPredicate ‣ NSSortDescription
  • 20. A picture says a 1000 words...
  • 22. MagicalRecord ‣ Writing Core Data code is tedious. ‣ You need quite a bit of boilerplate code to do something simple: NSManagedObjectContext  *moc  =  [self  managedObjectContext]; NSEntityDescription  *entityDescription  =  [NSEntityDescription  entityForName:@"Employee"  inManagedObjectContext:moc]; NSFetchRequest  *request  =  [NSFetchRequest  new]; [request  setEntity:entityDescription];   NSSortDescriptor  *sortDescriptor  =  [[NSSortDescriptor  alloc]  initWithKey:@"firstName"  ascending:YES]; [request  setSortDescriptors:@[sortDescriptor]];   NSError  *error; NSArray  *array  =  [moc  executeFetchRequest:request  error:&error]; if  (array) {   //  display  items  (eg  in  table  view) } else  {        //  Deal  with  error... }
  • 23. MagicalRecord ‣ MagicalRecord tries to solve this. ‣ = ActiveRecord pattern for Core Data. ‣ Encapsulates the tediousness of plain Core Data code.
  • 24. MagicalRecord ‣ Writing MagicalRecord enable code is tedious no more: ‣ That same example is now this: NSManagedObjectContext  *moc  =  [self  managedObjectContext]; NSArray  *array  =  [Employee  MR_findAllSortedBy:@"firstname"  ascending:YES  inContext:context]; if  (array) {   //  display  items  (eg  in  table  view) } else  {        //  Deal  with  error... }
  • 27. MagicalRecord + write less code + your code becomes more readable + good for apps requiring simple storage scenarios (=most apps, probably) + hides complexity - hides complexity - easy to start, but diving deeper becomes harder - uses defaults that are suboptimal in a multithreaded app - concurrency errors and issues are subtle
  • 28. MagicalRecord ‣ used MagicalRecord from the start ‣ Took me a while to find out the problems I was having were related to the complexity hiding ‣ The defaults are okay only for so much app complexity
  • 29. MagicalRecord ‣ That said: Magical Record is great. ‣ It will speed up your Core Data development by several factors. ‣ Also: take a look at mogenerator: ‣ http://rentzsch.github.com/mogenerator/ ‣ or: brew  install  mogenerator
  • 30. MagicalRecord ‣ So I threw it out.
  • 31. MagicalRecord ‣ So I threw it out. ‣ But not completely.
  • 32. MagicalRecord ‣ So I threw it out. ‣ But not completely. ‣ More about that later.
  • 33. The problems described hereafter only apply to the persistent stores with external backing (for example: sqlite).
  • 36. Problems? ‣ Core Data Objects are not thread safe.
  • 37. Problems? ‣ Core Data Objects are not thread safe. ‣ In essence: you can’t share them across threads (except for NSManagedObjectID).
  • 38. Problems? ‣ Core Data Objects are not thread safe. ‣ In essence: you can’t share them across threads (except for NSManagedObjectID). ‣ Core Data locks objects, even for read operations.
  • 39. Object storage is locked for read operations, too ‣ Objects used to power the UI must be fetched on the UI thread. ‣ Heavy/complex fetch requests (queries) block the UI thread while fetching the objects. You don’t want that.
  • 40. Objects aren’t supposed to be shared between threads ‣ The NSManagedObjectContext “locks” an object when you read one of its properties. ‣ This can cause a deadlock when you do access the same data from 2 threads. ‣ Reason: faulting support can change the object even while just reading from it. ‣ You can’t turn it off.
  • 42. Luckily, we can fix or workaround these problems.
  • 44. Keep to your thread
  • 45. Keep to your thread ‣ pre-iOS5: use thread confinement
  • 46. Keep to your thread ‣ pre-iOS5: use thread confinement ‣ iOS5 and later: use nested contexts
  • 47. Thread confinement ‣ In essence: keep an NSManagedObjectContext per thread ‣ Be very careful when going from one thread to another. ‣ MagicalRecord tries to hide this from you: ‣ It automatically provides a context for each thread ‣ This is a bit counterintuitive since you start mixing objects across threads quite easily.
  • 48. Thread confinement Image source: Cocoanetics
  • 49. Nested contexts ‣ Introduced in iOS5 ‣ Uses Grand Central Dispatch and dispatch queues ‣ Core Data manages threading for you ‣ Better than thread confinement ‣ more straightforward ‣ more flexible ‣ MagicalRecord hides this from you, too. ‣ Automatically switches to dispatch queues on iOS5 even though the API remains the same.
  • 50. Nested contexts Image source: Cocoanetics
  • 51. Nested contexts ‣ NSManagedObjectContext = cheap ‣ You can nest contexts ‣ Each context has its private dispatch queue ‣ No manual thread synchronization necessary
  • 52. Queue types ‣ NSConfinementConcurrencyType ‣ The old way (thread confinement) ‣ NSPrivateQueueConcurrencyType ‣ The context has its own private dispatch queue ‣ NSMainQueueConcurrencyType ‣ The context is associated with the main queue (or runloop, or UI thread) parentMoc  =  [[NSManagedObjectContext  alloc]  initWithConcurrencyType:NSMainQueueConcurrencyType]; [parentMoc  setPersistentStoreCoordinator:coordinator]; moc  =  [[NSManagedObjectContext  alloc]  initWithConcurrencyType:NSPrivateQueueConcurrencyType]; moc.parentContext  =  parentMoc;
  • 53. Thread safe? ‣ performBlock:   performBlockAndWait: ‣ Run a block you provide on the queue associated with the context. ‣ Object access in the block is thread safe [context  performBlockAndWait:^{        for  (Room*  room  in  [Room  findAllInContext:context])  {                room.joinedUsers  =  [NSSet  set];                room.knowsAboutJoinedUsersValue  =  NO;                room.unreadCountValue  =  0;                room.status  =  @"";        }        NSError*  error  =  nil;        [context  save:&error]; }];
  • 54. performBlock, and wait -­‐  (void)performBlock:(void  (^)())block; ‣ executes the block on the context dispatch queue as soon as possible ‣ nonblocking call ‣ code will not execute immediately -­‐  (void)performBlockAndWait:(void  (^)())block; ‣ executes the block on the context dispatch queue immediately ‣ blocks the current execution until block is done ‣ can cause a deadlock (if you’re already running code on the same queue)
  • 55. When to use what? ‣ performBlock: ‣ For actions which are “on their own” ‣ Consider the code in the block a Unit Of Work ‣ Best for save operations ‣ Useful for long fetches (use callbacks) ‣ performBlockAndWait: ‣ When you need stuff immediately ‣ Good for small fetches or “standalone” saves
  • 56. How is this better than thread confinement? ‣ No manual thread handling, Core Data handles it for you. ‣ More flexible: as long as you access managed objects in the correct context using performBlock: you’re pretty safe ‣ also applies to the main/UI thread! (unless you’re sure you’re on the main thread)
  • 57. Saving nested contexts ‣ Saves are only persisted one level deep. ‣ Parent contexts don’t pull changes from child contexts. ‣ Child contexts don’t see changes by parent contexts. ‣ Make them plenty and short-lived
  • 58. How to nest contexts ‣ 2 approaches: ‣ root context = NSMainQueueConcurrencyType ‣ root context = NSPrivateQueueConcurrencyType
  • 59. Root = Main ‣ Many child contents with private queues ‣ Root context on main queue ‣ Actual persistence happens on main queue, could block the UI Image source: Cocoanetics
  • 60. Root = Private ‣ Root context with private queue ‣ Many child contents with private queues ‣ context on main queue is child of root ‣ Actual persistence happens in background (does not block the UI) Image source: Cocoanetics
  • 61. What problems did we have again?
  • 62. What problems did we have again? ‣ No sharing of NSManagedObjects between threads.
  • 63. What problems did we have again? ‣ No sharing of NSManagedObjects between threads. ‣ Context locking
  • 64. Sharing: solution ‣ Pass only NSManagedObjectIDs to other threads, not objects. ‣ Refetch the object on a different thread or queue to work with it. ‣ Don’t forget to save the ‘original’ object first before working with it on the second thread or queue.
  • 65. Complex queries ‣ Use the same technique for complex or large queries. 1. do the heavy lifting in the background 2. pass list of NSManagedObjectIDs to another thread (e.g. UI thread). 3. load objects as faults, and let Core Data fault them in when you need them (e.g. when accessing a property) ‣ That’s lot of requests, but this is actually more performant and desirable in most cases.
  • 66. Locking: solution ‣ Use child contexts with their own dispatch queues. ‣ Use: performBlock: and performBlockAndWait:  carefully. ‣ Deadlocks still possible, especially with performBlockAndWait:
  • 67. A word about NSManagedObjectIDs ‣ Two types of IDs: ‣ temporary ‣ when the object hasn’t been persisted to a store ‣ permanent ‣ when the object has been persisted to a store
  • 68. A word about NSManagedObjectIDs ‣ Subtle bug: temporary IDs from a non-root context don’t get updated to permanent IDs when saving in the root context ‣ The object is saved just fine, but the ID is not updated correctly. ‣ When passing these around to other contexts after saving: you won’t find the object in another child context!
  • 69. A word about NSManagedObjectIDs ‣ To the rescue: -­‐  (BOOL)obtainPermanentIDsForObjects: (NSArray  *)objects  error:(NSError   **)error;
  • 70. A word about NSManagedObjectIDs -­‐  (BOOL)obtainPermanentIDsForObjects:(NSArray   *)objects  error:(NSError  **)error; ‣ Transforms objects with temporary IDs to permanent IDs (through the persistent store of the root context). ‣ Do this when creating a managed object and you’re safe. ‣ Obtaining permanentIDs is batched, so the performance hit is not that high
  • 71. MagicalRecord ‣ I still use MagicalRecord: ‣ Reduced form: no more “automatic” context handling --> dangerous! ‣ Added some extra sauce to work with the nested contexts. ‣ The methods MR supplies still allow for a speedup when coding.
  • 72. Useful References ‣ Nested context release notes: http://developer.apple.com/library/mac/#releasenotes/ DataManagement/RN-CoreData/_index.html ‣ Magical Record: https://github.com/magicalpanda/MagicalRecord ‣ Mogenerator: http://rentzsch.github.com/mogenerator/ ‣ A good read on Cocoanetics: http://www.cocoanetics.com/2012/07/multi-context-coredata/ ‣ Core data programming guide: http://developer.apple.com/library/mac/#documentation/ cocoa/Conceptual/CoreData/cdProgrammingGuide.html ‣ Butane: http://getbutane.com
  • 73. Thanks for listening. Questions? Contact me: Twitter: @inferis App.Net: @inferis E-mail: tom@interfaceimplementation.be vCard: http://inferis.org