Database Reference
In-Depth Information
In the
-mailRecipe
method, we construct a
PPRExportOperation
instance, passing it
the recipe. We then give the
PPRExportOperation
a completion block. The comple-
tion block is used to handle the results of the export operation. Note that the
block receives back both an
NSData
and an
NSError
. If the operation was success-
ful, the
NSData
is populated. If the operation failed for any reason, the
NSData
is
nil
, and the
NSError
is populated. In a production application, we would want
to respond to the error. For now, we have a developer-level logic check to
capture the error.
Building the PPRExportOperation
With the changes completed in the
PPRDetailViewController
, the next step is to
build the
PPRExportOperation
. The goal of the operation is to accept a single recipe
and turn it into a JSON structure. When the export is complete, the operation
will execute a completion block and pass the resulting data back to the caller.
This gives us the following header:
#import
"PPRRecipeMO.h"
typedef void
(^ExportCompletionBlock)(NSData *jsonData, NSError *error);
@interface
PPRExportOperation : NSOperation
@property
(nonatomic, copy) ExportCompletionBlock completionBlock;
- (id)initWithRecipe:(PPRRecipeMO*)recipe;
@end
The initializer for our export operation needs to retain only the
NSManagedObjectID
of the incoming
NSManagedObject
. Because the
initWithRecipe
method is being called
on the thread on which the incoming
NSManagedObject
was created, we can
access its methods. Once we are in our own
-main
method, we can no longer
access it. However, the
NSManagedObjectID
is thread-safe and can cross the
boundary. So, we grab it now and hold onto it in a property. We pass in the
entire
NSManagedObject
so that we can also grab a reference to the
NSPersistentStore-
Coordinator
without having to explicitly request it.
- (id)initWithRecipe:(PPRRecipeMO*)recipe;
{
if
(!(self = [super init]))
return
nil;
[self setIncomingRecipeID:[recipe objectID]];
NSManagedObjectContext *moc = [recipe managedObjectContext];
[self setPersistentStoreCoordinator:[moc persistentStoreCoordinator]];
return
self;
}