views:

763

answers:

3

I am using Core Data and I only want to fetch the first record in my dataset, is it possible?

+4  A: 
Tim
+1  A: 

Of course it partially depends on what you mean by the "first record". You may not only need to set the fetch limit to 1, but also to sort the results in the fetch.

For example, I have a bunch of User objects in my database, and I want to find the first one who created an account. (Assuming I already have the model for User, including one attribute named accountCreatedDate.)

NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"accountCreatedDate" ascending:YES]; // ascending YES = start with earliest date
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setSortDescriptors:sortDescriptors];
[request setFetchLimit:1];

NSArray *fetchResults = [managedObjectContext executeFetchRequest:request error:&error];

User *result = nil;

if ([fetchResults count]>0)
    result = [fetchResults objectAtIndex:0];

[request release];
[sortDescriptors release];
[sortDescriptor release];

If you don't sort the results before limiting the fetch, there's no telling what results will be returned "first".

Craig McMahon
A: 

This is my attempt. N.B. the Book Entity inherits from NSManagedObject.

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"isbn ==9780786660506"];

Book *book = (Book*) [CoreDataHelper getEntityFromFetchedResultsController:@"Book" :predicate :nil :YES :application.managedObjectContext];


if (book !=nil)    NSLog(@"book entity %@",book.title);

Bang this in a static helper class called CoreDataHelper

+ (NSManagedObject*)getEntityFromFetchedResultsController: (NSString*) entityName : (NSPredicate *) predicate : (NSString*) sortKey : (BOOL) sortAscending : (NSManagedObjectContext *) managedObjectContext
{

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
[request setEntity:entity]; 
[request setFetchLimit:1];

// If a predicate was passed, pass it to the query
if(predicate != nil)
{
    [request setPredicate:predicate];
}

// If a sort key was passed, use it for sorting.
if(sortKey != nil)
{
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];
    [sortDescriptors release];
    [sortDescriptor release];
}

NSError *error;

NSMutableArray *mutableFetchResults = [[[managedObjectContext executeFetchRequest:request error:&error] mutableCopy] autorelease];


    if (error !=nil){
NSLog(@"error %@", error);
}
   if ([mutableFetchResults count] >0)
    {
   NSManagedObject *firstObject = [mutableFetchResults objectAtIndex:0];
   return firstObject;
    }else
    {
      return nil;
    }

}    
johndpope