Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve single object from NSFetchRequest

I want to get a single object from my Core Data datastore, here is the code I have been using but it returns an array of objects. There must be a simpler and better way:

NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Manufacturer" inManagedObjectContext:managedObjectContext];
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"ManufacturerID==%@",[[mitems objectAtIndex:i] objectForKey:@"ManufacturerID"]];
[request setEntity:entity];
[request setPredicate:predicate];

NSError *error;
NSArray *entities = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
like image 824
Slee Avatar asked Aug 10 '10 22:08

Slee


1 Answers

If your predicate always fetches more than one result:

  • refine the predicate - don't forget you can build predicates with logic like AND/OR, simple equality is easy but may not be selective enough in your case.

  • just select the result you want from the array, it's no big deal - although if this is possible it should also be possible to refine the predicate...

  • consider reorganizing your data model so that you can refine the predicate to get just one item back.

The fetch always returns an array, that is its definition. However it can be an array of one object.

like image 87
Adam Eberbach Avatar answered Oct 13 '22 00:10

Adam Eberbach