How to fetch specific records in Core data

Anu Padhye picture Anu Padhye · Jul 9, 2014 · Viewed 7k times · Source

I am a new bid in iOS development. I am using NSManagedObject of Core Data to perform Insert and Fetch operations. It works perfectly fine. But the problem is, I want to fetch only some selected records (where condition in MySQL) from the table. For e.g. "select name from users where city='Pune'"; I found NSPredicate to fetch filtered data. But it gives all the data in array and not just the selected one. For e.g. if result for above query is:

Anu

Then the NSPredicate result will give:

fname = Anu
lname = Padhye
city = Pune
id = 3

Is there a way to only fetch selected record/s in iOS Objective-c? Following is the code snippet I am using for NSManagedObject:

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"User"];
    valueData = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];


NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:productEntity];
NSPredicate *p=[NSPredicate predicateWithFormat:@"id == %d", 3];
[fetch setPredicate:p];
    //... add sorts if you want them
NSError *fetchError;
NSArray *fetchedProducts=[valueData filteredArrayUsingPredicate:p];

Answer

CW0007007 picture CW0007007 · Jul 9, 2014

Try this:

 NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"User"];
 request.predicate = [NSPredicate predicateWithFormat:@"city == %@ && id == %d", @"Pune", 3];
 request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]];

 NSArray *results = [managedObjectContext executeFetchRequest:request error:nil];

Results array should now contain all records who have Pune as their city with the id of 3.