我正在尝试使用nspredicate来找到一个托管对象,其属性的==是我想要检查的值的值。
我确信这个值在我的数据模型中。
这就是我到目前为止尝试过的,但是结果数组计数总是为零。
-(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;
}
编辑
问题似乎与我的查询格式有关。
不过这管用吗?
NSExpression *exprName = [NSExpression expressionForKeyPath:@"userid"];
NSExpression *exprVal = [NSExpression expressionForConstantValue:data];
NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:exprName
rightExpression:exprVal
modifier:NSDirectPredicateModifier
type:NSEqualToPredicateOperatorType
options:0];
我不明白为什么一个起作用,另一个不起作用。他们都做同样的事对吧?
发布于 2011-05-27 13:20:56
不要把你的变量放在引号里。Parser Basics文档指出:
单个或双引用变量(或替换变量字符串)会导致%@、%K或$variable在格式字符串中被解释为文字,从而防止任何替换。
这应该可以做到:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userid == %@", attributeValue];
您可以在谓词编程指南中阅读更多有关谓词的内容。
https://stackoverflow.com/questions/6152327
复制相似问题