Fetch Objects from the Object Model

This is a Objective-C snippet, talking about coredata, NSFetchRequest and NSPredicate

Fetch Objects from the Object Model Add to Favorite

+(NSMutableArray *) searchObjectsInContext: (NSString*) entityName : (NSPredicate *) predicate : (NSString*) sortKey : (BOOL) sortAscending : (NSManagedObjectContext *) managedObjectContext
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
 
// If a predicate was passed, pass it to the query
if(predicate != nil)
{
[request setPredicate:predicate];
}
 
// If a sort key was passed, use it for sorting.
if(sortKey != nil)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
}
 
NSError *error;
 
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
 
[request release];
 
return mutableFetchResults;
}
 
+(NSMutableArray *) getObjectsFromContext: (NSString*) entityName : (NSString*) sortKey : (BOOL) sortAscending : (NSManagedObjectContext *) managedObjectContext
{
return [self searchObjectsInContext:entityName :nil :sortKey :sortAscending :managedObjectContext];
}

Fetching data from the object model is very easy, no SQL skills required, almost. To simplify fetching data and reducing the amount of code I created a simple helper class with static methods that do most of the work. //predicate = [NSPredicate predicateWithFormat:@"(ProvinceToCounty == %@)", selectedObject];

Created by ThePeppersStudio (52 days, 4.82 hours ago)

Do you want to leave a message? Please login first.