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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With