Skip to content

Instantly share code, notes, and snippets.

@indragiek
Created March 19, 2013 21:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indragiek/5200264 to your computer and use it in GitHub Desktop.
Save indragiek/5200264 to your computer and use it in GitHub Desktop.
Easy Core Data fetching/inserting
- (void)fetchWithRequest:(NSFetchRequest *)request
completion:(void(^)(NSArray *results, NSError *error))handler
{
[request setResultType:NSManagedObjectIDResultType];
void (^executeHandler)(NSArray *, NSError *) = ^(NSArray *results, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
if (handler) handler(results, error);
});
};
[self.backgroundContext performBlock:^{
NSError *error = nil;
NSArray *results = [self.backgroundContext executeFetchRequest:request error:&error];
if (error) executeHandler(nil, error);
else {
[self.mainQueueContext performBlock:^{
NSArray *objects = [self _transformBackgroundObjectIDsToMainQueueObjects:results];
executeHandler(objects, nil);
}];
}
}];
}
- (void)createObjectOfEntityName:(NSString *)entityName
configure:(void(^)(id object))configure
result:(void(^)(id object, NSError *error))result
{
[self.backgroundContext performBlock:^{
id object = [NSEntityDescription insertNewObjectForEntityForName:entityName
inManagedObjectContext:self.backgroundContext];
if (configure) configure(object);
__block NSError *error = nil;
[self.backgroundContext save:&error];
[self.mainQueueContext performBlockAndWait:^{
[self.mainQueueContext save:&error];
}];
[self.backgroundContext refreshObject:object mergeChanges:NO];
NSManagedObjectID *objectID = [object fgo_permanentObjectID];
[self.mainQueueContext performBlock:^{
NSError *existingError = nil;
NSManagedObject *managedObject = [self.mainQueueContext existingObjectWithID:objectID
error:&existingError];
if (existingError)
FGOGenericErrorLog(@"Error attempting to fetch object using the object ID. Trying a fetch request.", existingError);
if (!managedObject) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
request.predicate = [NSPredicate predicateWithFormat:@"SELF == %@", object];
request.fetchLimit = 1;
NSArray *results = [self.mainQueueContext executeFetchRequest:request error:&error];
managedObject = [results count] ? results[0] : nil;
}
if (result) result(managedObject, error);
}];
}];
}
- (void)fetchOrCreateObjectWithRequest:(NSFetchRequest *)request
configure:(void(^)(id object))configure
result:(void(^)(id object, NSError *error))result
{
request.fetchLimit = 1;
[self fetchWithRequest:request completion:^(NSArray *results, NSError *error) {
if (results.count) {
if (result) result(results[0], error);
} else {
[self createObjectOfEntityName:request.entityName configure:configure result:result];
}
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment