Created
February 6, 2012 13:01
-
-
Save vinzenzweber/1751941 to your computer and use it in GitHub Desktop.
CoreData - One method to conquer them all! Create fetch reeuests from string predicates.
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
/** | |
* Return an array with objects found in the local database for the given predicate. | |
*/ | |
-(NSArray *)fetchEntity:(NSString *)entityName withPredicateFormat:(NSString *)format, ... { | |
NSManagedObjectContext *managedObjectContext = [RKObjectManager sharedManager].objectStore.managedObjectContext; | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName | |
inManagedObjectContext:managedObjectContext]; | |
[request setEntity:entity]; | |
va_list args; | |
va_start(args, format); | |
NSPredicate *predicate = [NSPredicate predicateWithFormat:format arguments:args]; | |
va_end(args); | |
[request setPredicate:predicate]; | |
NSError *error = nil; | |
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error]; | |
if (error != nil) { | |
NSLog(@"ERROR FETCHING DATA FROM DB FOR PREDICATE"); | |
} | |
[request release]; | |
return array; | |
} | |
- (void)fetchObjects { | |
NSArray *array = [self fetchEntity:@"Vehicle" withPredicateFormat:@"latitude > %f AND latitude < %f AND longitude > %f AND longitude < %f", | |
latitudeStart, latitudeStop, longitudeStart, longitudeStop]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To query my sqlite database in Mac OS and iOS I am using lots of predicates and I hate to repeat myself. This method makes things easier in most cases.