Retrieve single object from NSFetchRequest

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.


It will always return an array but you can make it cleaner:

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;
//Making a mutable copy here makes no sense.  There is never a reason to make this mutable
//NSArray *entities = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
id manufacturer = [[managedObjectContext executeFetchRequest:request error:&error] lastObject];
request = nil;
NSAssert1(error && !manufacturer, @"Error fetching object: %@\n%@", [error localizedDescription], [error userInfo]);

-lastObject will return the last item in the array or nil if the array is empty. This keeps your code a little cleaner when you know there is going to be one object in the array or if you don't care what object you pull out of the array.

BTW, your property names should start with a lower case letter. I am surprised the compiler did not warn you about that.