Database Reference
In-Depth Information
main thread to let the main/UI NSManagedObjectContext “catch up.” With the
introduction of private queue contexts, this performance issue is finally solved.
If we start our Core Data stack with a private queue NSManagedObjectContext and
associate it with the NSPersistentStoreCoordinator , we can have the main/UI
NSManagedObjectContext as a child of the private queue NSManagedObjectContext .
Furthermore, when the main/UI NSManagedObjectContext is saved, it will not
produce a disk hit and will instead be nearly instantaneous. From there,
whenever we want to actually write to disk, we can kick off a save on the
private queue of the private context and get asynchronous saves.See Figure
17, Private queue for asynchronous saves , on page 96 .
Adding this ability to our application requires a relatively small change. First,
we need to add a property (nonatomic, strong) to hold onto our new private
NSManagedObjectContext . Next, we tweak the -initializeCoreDataStack a little bit.
Baseline/PPRecipes/PPRAppDelegateAlt1.m
NSPersistentStoreCoordinator *psc = nil;
psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
ZAssert(psc, @ "Failed to initialize persistent store coordinator" );
NSManagedObjectContext *private = nil;
NSUInteger type = NSPrivateQueueConcurrencyType;
private = [[NSManagedObjectContext alloc] initWithConcurrencyType:type];
[private setPersistentStoreCoordinator:psc];
type = NSMainQueueConcurrencyType;
NSManagedObjectContext *moc = nil;
moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:type];
[moc setParentContext:private];
[self setPrivateContext:private];
[self setManagedObjectContext:moc];
Before, we had one NSManagedObjectContext configured to be on the main queue
and writing to the NSPersistentStoreCoordinator . Now we have added a new
NSManagedObjectContext that is of type NSPrivateQueueConcurrencyType . We set the
NSPersistentStoreCoordinator to that private queue. Finally, we construct our main
queue NSManagedObjectContext . Instead of handing off the NSPersistentStoreCoordinator
to the main context, we give it a parent: the private queue context.
With that change, any saves on the main NSManagedObjectContext will push up
the changes only to the private queue NSManagedObjectContext . No writing to the
NSPersistentStoreCoordinator occurs. However, there are times when we really do
want to write to disk and persist our data changes. In that case, a couple of
other changes are in order.
 
 
 
Search WWH ::




Custom Search