Core Data – fetch a single entity

Posted on

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
        if ([objects count] > 0)
            match = (Target *)[objects objectAtIndex:0];

    [request release];

    return match;

Leave a Reply

Your email address will not be published.