Skip to content

Instantly share code, notes, and snippets.

@aidansteele
Created March 16, 2011 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidansteele/872056 to your computer and use it in GitHub Desktop.
Save aidansteele/872056 to your computer and use it in GitHub Desktop.
+ (id)fetchFirst:(BOOL)first managedObjectWithPredicateFormat:(NSString *)format, ... {
va_list args;
va_start(args, format);
return [self fetchFirst:first managedObjectWithPrefetchedKeyPaths:nil predicateFormat:format arguments:args];
va_end(args);
}
+ (id)fetchFirst:(BOOL)first managedObjectWithPrefetchedKeyPaths:(NSArray *)prefetched predicateFormat:(NSString *)format, ... {
va_list args;
va_start(args, format);
return [self fetchFirst:first managedObjectWithPrefetchedKeyPaths:prefetched predicateFormat:format arguments:args];
va_end(args);
}
+ (id)fetchFirst:(BOOL)first managedObjectWithPrefetchedKeyPaths:(NSArray *)prefetched predicateFormat:(NSString *)format arguments:(va_list)args {
NSManagedObjectContext *context = [NSManagedObjectContext IY_threadSpecificContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSString *entityName = NSStringFromClass([self class]);
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[fetchRequest setEntity:entity];
if (prefetched) {
[fetchRequest setRelationshipKeyPathsForPrefetching:prefetched];
}
if (format) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:format arguments:args];
[fetchRequest setPredicate:predicate];
}
NSError *error = nil;
NSArray *array = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
if (error) {
NSLog(@"%@", [error localizedDescription]);
}
if (first)
{
if ([array count] > 0) {
return [array objectAtIndex:0];
} else {
return nil;
}
} else {
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment