Database Reference
In-Depth Information
not normally need to have a reference to the
NSPersistentStore
after its creation,
let's just check the return for
nil
and continue.
Once this call is completed, our
NSPersistentStoreCoordinator
is fully initialized and
ready to be used. Since we have completed this step on a background queue,
it is helpful to notify the UI that it is ready to be used. Therefore, we end the
block with a call back onto the main queue and allow the UI to complete its
initialization. This completion could include removing a modal dialog or even
just telling the view controllers to reload themselves. The exact experience is
left up to the developer.
dispatch_sync(dispatch_get_main_queue(), ^{
[self contextInitialized];
});
});
Once we initialize the
NSPersistentStoreCoordinator
, we rarely, if ever, access it
directly again. It silently works in the background, persisting the data. Because
of this, we do not need to keep a reference to it directly in my
AppDelegate
;
instead, we can rely on the
NSManagedObjectContext
to do that for us.
1.3
NSManagedObjectContext
Next to
NSManagedObject
,
NSManagedObjectContext
is the object in the Core Data
stack that we'll most often access. The
NSManagedObjectContext
is the object we
access when we want to save to disk, when we want to read data into memory,
and when we want to create new objects. As shown in
Figure 4,
The Core Data
stack
, on page 9
, the
NSManagedObjectContext
is at the top of the Core Data
“stack” in that it is accessed directly by our code frequently. It is much less
common for us to need to go deeper into the stack.
NSManagedObjectContext
isn't thread-safe. Each thread that needs access to the
data should have its own
NSManagedObjectContext
. This is generally not an issue,
since most applications are not multithreaded or their multithreaded portions
do not need to interact with
NSManagedObjectContext
on any thread other than
the main thread. However, it is important to keep in mind that, like the UI,
NSManagedObjectContext
should be accessed only on the thread that created it,
which is generally the main thread.
NSManagedObjectContext *moc = nil;
NSManagedObjectContextConcurrencyType ccType = NSMainQueueConcurrencyType;
moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:ccType];
[moc setPersistentStoreCoordinator:psc];
[self setManagedObjectContext:moc];