Search code examples
objective-ccore-dataasynchronousblocknsmanagedobjectcontext

Use block with NSManagedObjectContext


I'm looking to use block with NSManagedObjectContext. I am trying to asynchronously download several images for one entity. The data structure I have is more or less like the following (this is pseudo-code and it is not exactly following NSManagedObject syntax).

@interface SAImageDoc : NSObject

@property(nonatomic, strong) NSString* imageUrl1;
@property(readwrite) BOOL imageUrl1Downloaded; 
@property(nonatomic, strong) NSString* imageUrl2;
@property(readwrite) BOOL imageUrl2Downloaded; 

@end

I am trying to asynchronous download the images using block (AFNetworking). After the image is downloaded, I would like to update the boolean value of downloaded to YES and save it to the CoreData.

The questions I have are:

  1. Is it ok to pass NSManagedObjectContext to each block? Since the block is executing in different threads, and NSManagedObjectContext is not thread-safe, it seems wrong to do that.
  2. Any suggestions how to handle this one? if 1 is not working. Any known examples?

Update

Given Gabriele, Mario's answer and referencing What is NSManagedObjectContext's performBlock: used for?, I believe here is what I shall do:

  1. instantiate context using NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType;
  2. in each block, call context performBlock.

Solution

  • To simply answer your question, you can pass the context to your download block and in that use the context's -performBlock: method to access the context.