Database Reference
In-Depth Information
Once the operation is started, we must perform a couple of start-up tasks.
First, since the operation is going to be executed on a separate thread, we
need to construct a new NSManagedObjectContext .
Baseline/PPRecipes/PPRExportOperation.m
- ( void )main
{
ZAssert([self completionBlock], @ "No completion block set" );
NSManagedObjectContext *localMOC = nil;
localMOC = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *psc = nil;
psc = [self persistentStoreCoordinator];
[localMOC setPersistentStoreCoordinator:psc];
Now that we have a local NSManagedObjectContext , we need to obtain a local copy
of the recipe. A call to -objectWithID: returns a local copy of the NSManagedObject .
We also confirm that it did return an object for us. -objectWithID: is a method
on NSManagedObjectContext that will return a context-local copy of the associated
NSManagedObject . If the NSManagedObject is already loaded into the context, then
it will return the object; otherwise, it will attempt to fetch it from the NSPersis-
tentStoreCoordinator .
Once we have a local copy of the recipe, we need to turn it into a JSON
structure. To do that, we must first convert the NSManagedObject into a dictionary.
However, we don't want to just grab the top-level object; we also want the
author, the ingredients, and so on. To get all of those, we'll have to do a bit
of recursive work.
Baseline/PPRecipes/PPRExportOperation.m
- (NSDictionary*)moToDictionary:(NSManagedObject*)mo
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if (!mo) return dict;
NSEntityDescription *entity = [mo entity];
NSArray *attributeKeys = [[entity attributesByName] allKeys];
NSDictionary *values = [mo dictionaryWithValuesForKeys:attributeKeys];
[dict addEntriesFromDictionary:values];
The first part of the conversion involves grabbing all of the attributes (strings,
numbers, dates) from the NSManagedObject and placing them into an NSMutable-
Dictionary . By utilizing KVC , we can do this with a small amount of code. We
first ask the NSEntityDescription for all of the attribute names, and then we call
-dictionaryWithValuesForKeys: on the NSManagedObject . This returns a dictionary with
all of the keys and values for the attributes. We then add the resulting dictio-
nary into our NSMutableDictionary .
 
 
 
Search WWH ::




Custom Search