tags:

views:

27

answers:

1

hi

i use CoreData to store datas, and i have got some entities. how can i do some custom statements through CoreData ? so exactly i mean i don't want to fetch all of records in datatable but for example "every elements where keyValue=something" and no more. or for example last 3 elements. etc, etc. so what way can i do custom statements to fetch required datas ?

A: 
// Init your fetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"entityName" inManagedObjectContext:yourManagedObjectContext];

// create the relation between request and the created entity
[fetchRequest setEntity:entityDescription]; 

// Set your predicate for this request
NSPredicate *somePredicate = [NSPredicate predicateWithFormat@"%K == %@", @"name", @"John"];
[fetchRequest setPredicate:somePredicate];

// Pushing the results into a array
NSError *error = nil;
NSArray *fetchResults = [yourManagedObjectContext executeFetchRequest:fetchRequest error:&error];

[fetchRequest release];

This example fetch all records from entity "entityName", which "name" attribute is equal to "John"

jamapag