fetch request for entity.attribute == @"somevalue"

jpgr picture jpgr · May 16, 2012 · Viewed 11.1k times · Source

How do I setup a fetch request to only pull the data from an entity's attribute with one particular value? This is the basic code I've used before.

-(void)fetchResults
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:self.entityDescription.name];
    NSString *cacheName = [self.entityDescription.name stringByAppendingString:@"Cache"];

    // predicate code
    if (self.predicate != nil) {
        [fetchRequest setPredicate:self.predicate];
    }
    // end of predicate code

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:cacheName];

    BOOL success;
    NSError *error;
    success = [self.fetchedResultsController performFetch:&error];
    if (!success)
    {
        NSLog(@"%@", [error localizedDescription]);
    }
}

I've been looking at this page: http://bit.ly/KevYwR is this the right direction?

Do I need to use NSPredicate or can I do without?

Thanks for any help, point in the right direction, etc.

Answer

Lorenzo B picture Lorenzo B · May 16, 2012

Setting up a NSFetchRequest is equivalent to a SELECT statetement in SQL language.

Here a simple example:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];

// error handling code

The array results contains all the managed objects contained within the sqlite file. If you want to grab a specific object (or more objects) you need to use a predicate with that request. For example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"attribute == %@", @"Some Value"];
[request setPredicate:predicate]; 

In this case results contains the objects where attribute is equal to Some Value. Setting a predicate is equal to put the WHERE clause in a SQL statement.

Note

I suppose that the name of the entity is EntityName and its property is called attribute which is of type string.

For further info I suggest you to read the Core Data programming guide and NSFecthRequest class reference.

Hope it helps.