Created
May 9, 2011 04:21
-
-
Save veritech/962046 to your computer and use it in GitHub Desktop.
NSMangedObjectContext async fetch requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
typedef void (^NSManagedObjectContextFetchCompleteBlock)(NSArray* results); | |
typedef void (^NSManagedObjectContextFetchFailBlock)(NSError *error); | |
@interface NSManagedObjectContext (NSManagedObjectContext_blocks) | |
-(void)executeFetchRequestInBackground:(NSFetchRequest*) aRequest | |
onComplete:(NSManagedObjectContextFetchCompleteBlock) completeBlock | |
onError:(NSManagedObjectContextFetchFailBlock) failBlock; | |
@end | |
@implementation NSManagedObjectContext (NSManagedObjectContext_blocks) | |
-(void)executeFetchRequestInBackground:(NSFetchRequest*) aRequest | |
onComplete:(NSManagedObjectContextFetchCompleteBlock) completeBlock | |
onError:(NSManagedObjectContextFetchFailBlock) failBlock{ | |
//Get the persistent store coordinator | |
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; | |
dispatch_queue_t backgroundQueue = dispatch_queue_create("FR.NSManagedObjectContext.fetchRequests", NULL); | |
dispatch_queue_t mainQueue = dispatch_get_main_queue(); | |
//Change the fetch result type to object ids | |
[aRequest setResultType:NSManagedObjectIDResultType]; | |
//Create a new context | |
dispatch_async(backgroundQueue, ^{ | |
//Create a new managed object context | |
NSManagedObjectContext *threadContext; | |
NSArray *threadResults = nil; | |
NSMutableArray *results = nil; | |
NSError *error = nil; | |
threadContext = [[NSManagedObjectContext alloc] init]; | |
[threadContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]]; | |
if( (threadResults = [threadContext executeFetchRequest:aRequest error:&error]) ){ | |
//Create a new array to place the results in | |
results = [[NSMutableArray alloc] initWithCapacity:[threadResults count]]; | |
//Call on the main thread | |
dispatch_sync(mainQueue, ^{ | |
//Iterate over the objects | |
//Re assign the objects to the correct (main) context | |
[threadResults enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *halt){ | |
[results addObject:[self objectWithID:obj]]; | |
}]; | |
completeBlock(results); | |
}); | |
[results release]; | |
} | |
else{ | |
//Call on the main thread | |
dispatch_sync(mainQueue, ^{ | |
failBlock( error ); | |
}); | |
} | |
//As the call back blocks are processed synchronously this should be safe | |
[threadContext release]; | |
}); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment