Skip to content

Instantly share code, notes, and snippets.

@buh
Created March 26, 2014 11:43
Show Gist options
  • Save buh/9781426 to your computer and use it in GitHub Desktop.
Save buh/9781426 to your computer and use it in GitHub Desktop.
Core Data Fetch Async
@implementation NSManagedObject (ManagedObject)
+ (void)fetchAsyncToMainContextWithRequest:(void (^)(NSFetchRequest *request))block
completion:(void (^)(NSArray *objects))completion
{
if (!completion) {
return;
}
NSManagedObjectContext *mainContext = [NSManagedObjectContext mainContext];
NSManagedObjectContext *backgroundContext = [NSManagedObjectContext backgroundContext];
[backgroundContext performBlock:^{
NSFetchRequest *backgroundRequest = [NSFetchRequest fetchRequestWithEntity:[self class] context:backgroundContext];
if (block) {
block(backgroundRequest);
}
[backgroundRequest setResultType:NSManagedObjectIDResultType];
NSError *error = nil;
NSArray *backgroundObjects = [backgroundContext executeFetchRequest:backgroundRequest error:&error];
if (!error) {
[mainContext performBlock:^{
NSMutableArray *objects = [NSMutableArray array];
[backgroundObjects enumerateObjectsUsingBlock:^(NSManagedObjectID *objId, NSUInteger idx, BOOL *stop) {
[objects addObject:[mainContext objectWithID:objId]];
}];
completion([objects copy]);
}];
}
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment