Last Updated: February 25, 2016
·
2.339K
· flexicoder

Core Data - fetch a single entity

I’ve used the following code to retrieve an entity from Core Data, so that the result returns the entity object rather than a Dictionary

 -(Target *) currentTargetInContext:(NSManagedObjectContext *)context  {
    Target *match;

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName: @"Target" inManagedObjectContext:context];
    [request setEntity:entity];

    [request setResultType:NSManagedObjectResultType];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Achieved == 0 "];
    [request setPredicate:predicate];

    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    match = nil;
    if (objects == nil)
    {
        // handle the error
    }
    else
    {
        if ([objects count] > 0)
        {
            match = (Target *)[objects objectAtIndex:0];
        }
    }

    [request release];

    return match;
}

http://www.flexicoder.com/blog/index.php/2009/09/core-data-fetch-a-single-entity/