【问题标题】:NSPredicate for max(arrayOfNSDates)最大值的 NSPredicate (arrayOfNSDates)
【发布时间】:2011-09-27 08:42:22
【问题描述】:
【问题讨论】:
标签:
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 等)