How to fetch a single object from Coredata using a predicate
What about the fetchLimit
on the fetchRequest
You can set that to 1
The fetch limit specifies the maximum number of objects that a request should return when executed.
E.g. in Swift:
let fetchRequest = NSFetchRequest(entityName: "Cart")
fetchRequest.fetchLimit = 1
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(Cart.creationDate), ascending: true)]
Edit: The sortDescriptors
are set only because I was using this fetchRequest
with an NFRC, you can just execute the fetchRequest
too:
do {
let fetchRequest = NSFetchRequest(entityName: "Cart")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "name == %@", mainCart)
var objects: [Cart]
try objects = mainMoc.execute(fetchRequest) as! [Cart]
} catch {
}
Import NSManagedObject(InstallProject) and fetch one object like this,
-(InstallProject *)readSelectedInstall:(NSString *)projIDString
{
NSArray *fetchedObjects;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"InstallProject" inManagedObjectContext: context];
[fetch setEntity:entityDescription];
[fetch setPredicate:[NSPredicate predicateWithFormat:@"(ANY ProjID contains[cd] %@)",projIDString]];
NSError * error = nil;
fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
return [fetchedObjects objectAtIndex:0];
else
return nil;
}