【问题标题】:issue in NSPredicate for NSStringNSPredicate 中 NSString 的问题
【发布时间】:2014-03-06 07:46:10
【问题描述】:

在我的应用程序中,我使用 CoreData。Amount 值作为 NSString 存储在 coreData 中。在我的界面生成器中,我有两个文本字段。当我在我的文本字段上输入任何金额时,此金额将接受为最小值和最大值。我想获取我输入的最小和最大金额之间的所有金额。

解决方案是什么。我只是通过这种方式Example 它不适用于我的项目,因为我想在我的 NSPredicate 方法上将字符串转换为整数。

我的代码是

 NSPredicate *p1= [NSPredicate predicateWithFormat:@"(amount.intValue => %@) && (amount.intValue <=%@)", text1.intValue,text2.intValue]];

注意,数量在 coredata 中存储为 NSString

【问题讨论】:

  • 你试过(amount.intValue =&gt; %d)这个吗?
  • 您是否尝试使用此谓词从数据库中获取数据?或过滤从数据库中获取的数据?
  • 为什么将金额存储为NSString?可以改成NSNumber
  • 你得到任何错误,还是结果只是空的?
  • 金额取自核心数据。为什么我们这样称呼amount.text1

标签: ios objective-c core-data ios7 nspredicate


【解决方案1】:

NSPredicate *p1= [NSPredicate predicateWithFormat:@"(amount.intValue => %@) && (amount.intValue

您不应该比较数字和字符串。比较一个或另一个。在这种情况下,您想要比较数字。您应该将存储在模型中的源数据更改为数字。

=&gt; 应该是&gt;=

%d是整数参数格式,text1.intValue返回整数。使用 %@ 会让人开玩笑,不会做你想做的事。

记录谓词的内容,以便查看它包含的内容。但主要是改变模型中数据的类型。

【讨论】:

  • "=> 应该是 >="Both syntaxes are supported。但为了保持一致性,我同意。
  • 我在 coredata 上将 NSString 格式更改为 NSNumber(double)。希望对 nspredicate 进行哪些更改
  • 试试:NSPredicate *p1= [NSPredicate predicateWithFormat:@"(amount &gt;= %d) &amp;&amp; (amount &lt;= %d)", text1.intValue, text2.intValue]];
【解决方案2】:

由于您将金额存储为 NSString,因此在进行评估时需要将其作为 NSNumber 传递。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.intValue <= $max.intValue AND SELF.intValue >= $min.intValue"];

现在您可以评估金额以查看它是否在范围内

if ([predicate evaluateWithObject:[NSNumber numberWithInt:amount.intValue] substitutionVariables:@{@"max":[NSNumber numberWithInt:text1.intValue], @"min":[NSNumber numberWithInt:text2.intValue]}])
{
    //Got the correct amount
}

【讨论】:

    【解决方案3】:

    正确答案是

    NSPredicate *p1= [NSPredicate predicateWithFormat:@"(amount >= %d) && (amount <= %d)", text1.intValue, text2.intValue]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多