Created
May 20, 2013 20:07
-
-
Save sebreh/5615091 to your computer and use it in GitHub Desktop.
Category for executing a Core Data fetch request in the background
This file contains 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 <CoreData/CoreData.h> | |
@interface NSManagedObjectContext (SRFetchAsync) | |
- (void)sr_executeFetchRequest:(NSFetchRequest *)request completion:(void (^)(NSArray *objects, NSError *error))completion; | |
@end |
This file contains 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 "NSManagedObjectContext+SRFetchAsync.h" | |
@implementation NSManagedObjectContext (SRFetchAsync) | |
- (void)sr_executeFetchRequest:(NSFetchRequest *)request completion:(void (^)(NSArray *objects, NSError *error))completion { | |
NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator; | |
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; | |
[backgroundContext performBlock:^{ | |
backgroundContext.persistentStoreCoordinator = coordinator; | |
// Fetch into shared persistent store in background thread | |
NSError *error = nil; | |
NSArray *fetchedObjects = [backgroundContext executeFetchRequest:request error:&error]; | |
[self performBlock:^{ | |
if (fetchedObjects) { | |
// Collect object IDs | |
NSMutableArray *mutObjectIds = [[NSMutableArray alloc] initWithCapacity:[fetchedObjects count]]; | |
for (NSManagedObject *obj in fetchedObjects) { | |
[mutObjectIds addObject:obj.objectID]; | |
} | |
// Fault in objects into current context by object ID as they are available in the shared persistent store | |
NSMutableArray *mutObjects = [[NSMutableArray alloc] initWithCapacity:[mutObjectIds count]]; | |
for (NSManagedObjectID *objectID in mutObjectIds) { | |
NSManagedObject *obj = [self objectWithID:objectID]; | |
[mutObjects addObject:obj]; | |
} | |
if (completion) { | |
NSArray *objects = [mutObjects copy]; | |
completion(objects, nil); | |
} | |
} else { | |
if (completion) { | |
completion(nil, error); | |
} | |
} | |
}]; | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm getting freezing issue when this code implemented with my project. can you please point out what is wrong with my code?
}