简体   繁体   English

NSPredicate == 查询

[英]NSPredicate == query

I'm trying to use nspredicate to find a managed object whose attribue's vale is == to a value I want to check.我正在尝试使用 nspredicate 来查找托管 object ,其属性值 == 到我要检查的值。

I know for certain that the value is in my data model.我确定该值在我的数据 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: Parser Basics 的文档指出:

Single or double quoting variables (or substitution variable strings) cause %@, %K, or $variable to be interpreted as a literal in the format string and so prevent any substitution.单引号或双引号变量(或替换变量字符串)会导致 %@、%K 或 $variable 被解释为格式字符串中的文字,从而防止任何替换。

This should do it:这应该这样做:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userid == %@", attributeValue];

You can read more about predicates in the Predicate Programming Guide .您可以在Predicate Programming Guide中阅读有关谓词的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM