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/
Written by Paul Ledger
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Objective c
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#