Databases Reference
In-Depth Information
quite straightforward and is nearly identical to the creation of the NSManagedOb-
jectContext on the main thread.
Baseline/PPRecipes/PPRImportOperation.m
NSManagedObjectContext *localMOC = nil;
NSPersistentStoreCoordinator *psc = nil;
localMOC = [[NSManagedObjectContext alloc] init];
psc = [[self mainContext] persistentStoreCoordinator];
[localMOC setPersistentStoreCoordinator:psc];
As shown in the method -main , we grab a reference to the existing NSPersistentStore-
Coordinator and use that in the initialization of a new NSManagedObjectContext .
Although the NSPersistentStoreCoordinator is not thread-safe either, the NSManage-
dObjectContext knows how to lock it properly when in use. Therefore, we can
attach as many NSManagedObjectContext instances to a single NSPersistentStoreCoor-
dinator as we want without fear of collision.
Joe asks:
When Do I Need to Worry About Threading?
The point at which threading is appropriate is a hard one to decide upon. As a rule,
I will put an operation into another thread any time that it blocks the UI thread from
drawing or causes the operating system to think that the application is nonresponsive.
When an application starts freezing or stuttering, it's time to optimize the application
and look at threading. As your experience grows, it becomes easier to spot these
trouble points ahead of time.
Cross-thread Communication
There is one major catch when standing up multiple NSManagedObjectContext
instances. Each instance is unaware of the existence and activity of the other
instances. This means that when an NSManagedObject is created, edited, or
deleted by one NSManagedObjectContext , the other instances aren't aware of the
change.
Fortunately, Apple has given us a relatively easy way to keep all the NSManage-
dObjectContext instances in sync. Every time an NSManagedObjectContext completes
a save operation, it broadcasts an NSNotification with the key NSManagedObjectCon-
textDidSaveNotification . In addition, the NSNotification instance contains all the
information about what is occurring in that save.
To complement the NSNotification broadcast, the NSManagedObjectContext has a
method designed to consume this NSNotification and update itself based on its
 
 
 
Search WWH ::




Custom Search