ios NSPredicate 与整数比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7540329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:37:24  来源:igfitidea点击:

NSPredicate compare with Integer

ioscore-datanspredicate

提问by wolfrevo

How can I compare two NSNumbers or a NSNumber and an Integer in an NSPredicate?

如何在 NSPredicate 中比较两个 NSNumber 或一个 NSNumber 和一个整数?

I tried:

我试过:

NSNumber *stdUserNumber = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@"standardUser"]];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userID == %@", stdUserNumber];

Well, this doesn't work ... anyone has an idea how to do it? I'm sure it's pretty easy but I wasn't able to find anything ...

好吧,这不起作用……有人知道该怎么做吗?我确定这很容易,但我找不到任何东西......

回答by EmptyStack

NSNumberis an object type. Unlike NSString, the actual value of NSNumberis not substitued when used with %@format. You have to get the actual value using the predefined methods, like intValuewhich returns the integer value. And use the format substituer as %das we are going to substitute an integer value.

NSNumber是一个对象类型。与 不同NSStringNSNumber的实际值在与%@format 一起使用时不会被替换。您必须使用预定义的方法获取实际值,例如intValue返回整数值。并使用格式替换器,%d因为我们将替换一个整数值。

The predicate should be,

谓词应该是,

predicateWithFormat:@"userID == %d", [stdUserNumber intValue]];

回答by Josip B.

If you are using predicateWithSubstitutionVariables: and value you want to predicate is NSNumber with integer value then you need to use NSNumber in predicate instead of NSString as substitution value. Take a look at example:

如果您使用 predicateWithSubstitutionVariables: 并且您想要谓词的值是 NSNumber 和整数值,那么您需要在谓词中使用 NSNumber 而不是 NSString 作为替换值。看一个例子:

NSPredicate *genrePredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"genreID == $GENRE_ID"]]; //if we make only one NSPredicate if would look something like this: [NSPredicate predicateWithFormat:@"genreID == %d", [someString integerValue]];

NSPredicate *localPredicate = nil;
for(NSDictionary *genre in genresArray){
    localPredicate = [genrePredicate predicateWithSubstitutionVariables:@{@"GENRE_ID" : [NSNumber numberWithInteger:[genre[@"genre_id"] integerValue]]}];
}