Iphone NSPredicate==查询
我正在尝试使用nspredicate查找一个托管对象,该对象的属性值为==我要检查的值 我确信这个值在我的数据模型中 这是我到目前为止尝试过的,但结果数组计数始终为零Iphone NSPredicate==查询,iphone,objective-c,ios,core-data,nspredicate,Iphone,Objective C,Ios,Core Data,Nspredicate,我正在尝试使用nspredicate查找一个托管对象,该对象的属性值为==我要检查的值 我确信这个值在我的数据模型中 这是我到目前为止尝试过的,但结果数组计数始终为零 -(BOOL)checkIfFavouriteExists:(NSString *)data { BOOL returnvalue; NSFetchRequest *fetchReq = [[NSFetchRequest alloc]init]; NSString *attributeName = @"
-(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];
我不明白为什么一个有效,另一个无效。它们都做了同样的事情,对吗?不要把变量放在引号里。各国: 单引号或双引号变量(或 替换变量(字符串)原因 %@要解释的、%K或$variable 以字符串和 因此,防止任何替代 这应该做到:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userid == %@", attributeValue];
您可以在中阅读有关谓词的更多信息 不要用引号括起变量。各国: 单引号或双引号变量(或 替换变量(字符串)原因 %@要解释的、%K或$variable 以字符串和 因此,防止任何替代 这应该做到:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userid == %@", attributeValue];
您可以在中阅读有关谓词的更多信息 您是否尝试从-executeFetchRequest:error:捕获错误?您使用谓词格式的单个
=
进行了尝试?请尝试以下操作,[NSPredicate predicateWithFormat:@“%@=%@”、attributeName、attributeValue]
@SImon,我找到了解决方案,但我也会尝试您的:)您是否尝试从-executeFetchRequest:error:?您尝试过谓词格式的单个=
?尝试一下,[NSPredicate predicateWithFormat:@“%@=%@”,attributeName,attributeValue]代码>@SImon,我找到了解决方案,但我也会试试你的:)