【问题标题】:NSPredicate compare with IntegerNSPredicate 与整数比较
【发布时间】:2011-11-24 07:34:46
【问题描述】:

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

我试过了:

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

好吧,这行不通……有人知道怎么做吗? 我敢肯定这很容易,但我找不到任何东西......

【问题讨论】:

    标签: ios objective-c core-data nspredicate


    【解决方案1】:

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

    谓词应该是,

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

    【讨论】:

    • 非常感谢您!是否有所有这些 %d %i %@ %...“快捷方式”的列表?
    • ... 这应该没什么区别。谓词格式解析器将在格式字符串中看到%d,从va_list 中弹出一个int,然后将其装入NSNumber
    • 这很奇怪,因为我也试过: fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userID == %i", [[NSUserDefaults standardUserDefaults] integerForKey:@"standardUser"]]];那没有用......所以它必须是 %d !? ...无论如何,它现在正在工作:)
    • 这确实为我节省了一些时间。由于我是在 swift 中编写大部分代码并且只使用 %@ 来定义谓词,所以我完全忘记了我们需要使用正确的格式替换。
    • 这里是所有格式说明符的列表:developer.apple.com/library/content/documentation/Cocoa/…
    【解决方案2】:

    如果您使用 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]]}];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多