Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific data in Core Data?

I have a sample program that use Core Data and load an sqlite database in it. And I am displaying all the values using this code

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Name"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

for (Name *name in fetchedObjects) {
    NSLog(@"ID: %@", name.nameId);
    NSLog(@"First Name: %@", name.first);
    NSLog(@"Middle Name: %@", name.middle);
    NSLog(@"Last Name: %@", name.last);
}

This code works fine, my problem here is that I can't select a specific data/record. Example I want to select the record with the ID = 1.

Thanks!

like image 960
kimbebot Avatar asked Jul 03 '12 07:07

kimbebot


People also ask

How do I get data from Core Data?

Fetching Data From CoreData We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context. fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.

Can we set primary key in Core Data?

The answer is NO.

What are fetched properties 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.

How do I use Core Data?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.


1 Answers

You have to use predicates (with NSPredicate) before your request execution.

Something like that :

NSPredicate *predicateID = [NSPredicate predicateWithFormat:@"nameID == %d",-1];
[fetchRequest setPredicate:predicateID];
like image 187
Pierre Avatar answered Oct 06 '22 17:10

Pierre