我正在使用以下代码尝试获取请求:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dateModified > CAST(CAST(now(), \"NSNumber\") - %d, \"NSDate\")", (30*86400)];
NSFetchRequest *itemRequest = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
[itemRequest setPredicate:predicate];
NSArray *items = [[self managedObjectContext] executeFetchRequest:itemRequest error:nil];
...为了获取'dateModified>的项目| now() - 30天|'。问题是上面的谓词正常工作(正确提取),直到我将NSPersistentDocument保存为SQLite并重新打开文档。当我重新打开文档时,我收到以下错误:
不支持的函数表达式CAST(CAST(now(),“NSNumber”) - 2592000,“NSDate”)
为什么这个谓词在保存之前正常运行,或者我将文档保存为XML,但如果我保存为SQLite则无法正常工作?有没有办法将此谓词与SQlite商店类型一起使用?
P.S。我也尝试使用以下代码形成谓词,但得到相同的错误:
//"now()" is a function and takes no arguments
NSExpression * now = [NSExpression expressionForFunction:@"now" arguments:[NSArray array]];
//CAST(now(), 'NSNumber')
NSArray * castNowArguments = [NSArray arrayWithObjects:now, [NSExpression expressionForConstantValue:@"NSNumber"], nil];
NSExpression * castNow = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castNowArguments];
//CAST(now(), 'NSNumber') [+/-] {a time interval}
NSArray * relativeTimestampArguments = [NSArray arrayWithObjects:castNow, [NSExpression expressionForConstantValue:[NSNumber numberWithDouble:(30*86400)]], nil];
NSExpression * relativeTimestamp = [NSExpression expressionForFunction:@"from:subtract:" arguments:relativeTimestampArguments];
//CAST(CAST(now(), 'NSNumber') [+/-] {a time interval}, 'NSDate')
NSArray * castToDateArguments = [NSArray arrayWithObjects:relativeTimestamp, [NSExpression expressionForConstantValue:@"NSDate"], nil];
NSExpression * castToDate = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castToDateArguments];
NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"dateModified"]
rightExpression:castToDate
modifier:NSDirectPredicateModifier
type:NSGreaterThanOrEqualToComparison
options:0];
答案 0 :(得分:2)
我找到了自己的解决方案......
从SQLite商店类型获取数据时,不支持函数调用。只能在提取内存数据时使用函数调用。为了仍然使用这个谓词,我必须首先获取数据集,然后使用:
过滤数组[allItems filteredArrayUsingPredicate:predicate];
希望这有助于某人!
答案 1 :(得分:0)
以下代码在我的案例中得到了很好的解决:
now() - 2592000