Skip to content

Instantly share code, notes, and snippets.

@vinzenzweber
Created February 6, 2012 13:01
Show Gist options
  • Save vinzenzweber/1751941 to your computer and use it in GitHub Desktop.
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.
/**
* 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];
}
@vinzenzweber
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment