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

How to configure a query to retrieve data from only an attribute of an object with one specific value? This is the base code I 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 looked 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.

+7
source share
1 answer

Setting up a NSFetchRequest equivalent to SELECT status in SQL.

Here is 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 results array contains all of the managed objects contained in the sqlite file. If you want to capture a specific object (or more objects), you need to use a predicate with this query. For example:

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

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

Note

I assume that the name of the EntityName object and its property is called attribute , which has a type string.

For more information, I suggest you read the Master Data Programming Guide and the link to NSFecthRequest .

Hope this helps.

+19
source

All Articles