Database Reference
In-Depth Information
Concurrency Types
There are a few requirements that must be satisfied in order to use parent
and child contexts. Each
NSManagedObjectContext
that is associated in this way
must be initialized with the new
-initWithConcurrencyType:
initializer. A concurrency
type describes how an
NSManagedObjectContext
can be interacted with, because
that relates to threading. Three concurrency types are available.
NSMainQueueConcurrencyType
The first type is called
NSMainQueueConcurrencyType
. This concurrency type is
formally declared as accessible only from the main thread. An
NSManagedObject-
Context
that is being used by the user interface should be defined with this
concurrency type. It does not matter what thread we are currently on when
we initialize an
NSManagedObjectContext
with this concurrency type because it
must always be used on the main thread.
When accessed on the main thread, it can be treated normally. All access is
available. However, if it is accessed from a background/nonmain thread, it
can be accessed only via the
-performBlock:
and
-performBlockAndWait:
methods.
NSPrivateQueueConcurrencyType
The private queue concurrency type creates an
NSManagedObjectContext
that can
be accessed
only
from its private queue. Because the queue is private, the
NSManagedObjectContext
can be used only via the
-performBlock:
and
-performBlockAnd-
Wait:
methods.
NSConfinementConcurrencyType
The confinement concurrency type is the “normal” concurrency type. When
an
NSManagedObjectContext
is initialized using the
-init
method, this is the concur-
rency type that is configured. A confinement concurrency type means that
the
NSManagedObjectContext
is confined to the thread that created it. If the
NSManagedObjectContext
is accessed from a thread other than the one that created
it, an exception is thrown.
Let's walk through a couple of changes to our application in order to demon-
strate the benefits of these new features.
Asynchronous Saving
One of the biggest issues with threading prior to iOS 6.0 and Mac OS X 10.8
Mountain Lion had to do with
thread blocking
. No matter how cleverly we
wrote our import and export operations, sooner or later we
had to
block the