Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch specific records in Core data

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];
like image 949
Anu Padhye Avatar asked Jul 09 '14 12:07

Anu Padhye


People also ask

What is fetched property in Core Data?

Fetched Properties in Core Data are properties that return an array value from a predicate. A fetched property predicate is a Core Data query that evaluates to an array of results.

What class would you use to filter fetched results from Core Data?

You can use . filter on the fetchedResults. Yes you can, but that's a Swift function. Using NSDelegate delegates filtering to Core Data which can be more efficient, especially on large data sets.

What is NSFetchRequest in Swift?

A description of search criteria used to retrieve data from a persistent store.


1 Answers

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.

like image 135
CW0007007 Avatar answered Oct 08 '22 01:10

CW0007007