Created
March 16, 2011 05:23
-
-
Save aidansteele/872056 to your computer and use it in GitHub Desktop.
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
+ (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