Skip to content

Instantly share code, notes, and snippets.

@yasirmturk
Created November 30, 2011 07:27
Show Gist options
  • Save yasirmturk/1408335 to your computer and use it in GitHub Desktop.
Save yasirmturk/1408335 to your computer and use it in GitHub Desktop.
A generic core data function that can query given entity with the given condition & return sorted results
/*
* A generic function that can query that given entity with the given condition and return sorted results.
*/
-(NSArray *)queryDBForEntity:(NSString *)entityName predicate:(NSPredicate *)predicate sortByField:(NSString *)sortField
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
if(sortField != nil)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortField ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
}
if(predicate != nil)
[request setPredicate:predicate];
NSError *error;
// NSMutableArray *mutableFetchResults = [[[self managedObjectContext] executeFetchRequest:request error:&error] mutableCopy];
NSArray *fetchResults = [[self managedObjectContext] executeFetchRequest:request error:&error];
[request release];
if (fetchResults == nil) {
NSLog(@"Error fetching result %@", [error description]);
}
return fetchResults;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment