I’m trying to use nspredicate to find a managed object whose attribue’s vale is == to a value I want to check.
I know for certain that the value is in my data model.
This is what I have tried so far but the results array count is always zero.
-(BOOL)checkIfFavouriteExists:(NSString *)data
{
BOOL returnvalue;
NSFetchRequest *fetchReq = [[NSFetchRequest alloc]init];
NSString *attributeName = @"userid";
NSString *attributeValue = data;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == '%@'",
attributeName, attributeValue];
//setting the predicate to the fetch request
[fetchReq setPredicate:predicate];
[fetchReq setEntity:[NSEntityDescription entityForName:@"Favourites" inManagedObjectContext:self.managedObjectContext]];
NSMutableArray *resultArray = [[NSMutableArray alloc]initWithArray:[self.managedObjectContext executeFetchRequest:fetchReq error:nil]];
if([resultArray count]>0)
{
returnvalue=YES;
} else
{
NSLog(@"No records");
returnvalue=NO;
}
return returnvalue;
}
EDIT
The problem seems to be with my query format.
This works though?
NSExpression *exprName = [NSExpression expressionForKeyPath:@"userid"];
NSExpression *exprVal = [NSExpression expressionForConstantValue:data];
NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:exprName
rightExpression:exprVal
modifier:NSDirectPredicateModifier
type:NSEqualToPredicateOperatorType
options:0];
I dont understand why one works and the other does not. They both do the same thing right?
Don’t put your variables in quotes. The documentation on Parser Basics states:
This should do it:
You can read more about predicates in the Predicate Programming Guide.