【问题标题】:NSPredicate for max(arrayOfNSDates)最大值的 NSPredicate (arrayOfNSDates)
【发布时间】:2011-09-27 08:42:22
【问题描述】:

我遇到了 NSPredicate 的问题。

我有一些引擎,其中谓词是根据来自 Web 服务的定义构造的。

我使用类似的东西:

[NSPredicate predicateWithFormat:@"max({1,2,3})==3"]

很好,但我需要 NSDate 对象的 max 函数。 这里http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSExpression_Class/Reference/NSExpression.html#//apple_ref/doc/uid/TP30001190 写的是 max() 函数只能获取包含表示数字的对象的数组。

是否有任何解决方案可以为此使用此功能(覆盖一些方法,为 NSPredicate 创建一些类别)

提前致谢。

【问题讨论】:

    标签: iphone nsdate nspredicate max


    【解决方案1】:

    好的,这是可能的,但很奇怪。我们必须以编程方式构建格式字符串。或者,我们可以通过创建单独的 NSExpression 对象来构建它,但这会产生更多代码(尽管可能更安全,但无论如何)。

    NSDate *maxDate = ...; 
    NSArray *arrayOfDates = ...; // an NSArray of NSDate objects
    
    NSMutableArray *dateFormats = [NSMutableArray array];
    for (NSDate *date in arrayOfDates) {
      NSString *format = [NSString stringWithFormat:@"%f", [date timeIntervalSinceReferenceDate]];
      [dateFormats addObject:format];
    }
    
    NSString *dateFormatString = [dateFormats componentsJoinedByString:@","];
    NSString *format = [NSString stringWithFormat:@"CAST(max({%@}) = %%@, 'NSDate')", dateFormatString];
    
    // format now looks like CAST(max({xxxx.xxxx, nnnn.nnnn, aaaa.aaaa, ....}), 'NSDate') = %@
    
    NSPredicate *datePredicate = [NSPredicate predicateWithFormat:format, maxDate];
    

    这里的技巧是使用日期自参考日期以来的绝对时间间隔作为 max() 函数的参数,然后使用 @987654325 将 that 的结果转换回日期@。有关如何使用带有日期的 CAST() 函数的更多信息,请参阅 in this blog post

    【讨论】:

      【解决方案2】:

      这个解决方案非常好,但不能解决我的问题。 我得到了这样的东西:

      NSPredicate* predicate = [NSPredicate predicateWithFormat: condition];
      [predicate evaluateWithObject:nil substitutionVariables: currentForm];
      

      条件可以是:

      max($widgetWhichReturnDate.result.result,$widgetWhichReturnDate.result) 
      

      max($widgetWhichReturnInt.result,$widgetWhichReturnInt1.result)
      

      这里使用的小部件取决于 web 服务。 所以我不喜欢对 Date 和 int 使用不同的函数(或者将来可能是 float、double 等)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-02
        • 1970-01-01
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多