【问题标题】:Function for NSExpression using 'now'使用“现在”的 NSExpression 函数
【发布时间】:2012-02-02 19:28:07
【问题描述】:

我的ManagedObject 中有一个NSDate 数组,我想使用稍后只给我NSDate 的表达式创建一个NSFetchRequest

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"eventDate"];
NSExpression *futureDateExpression = [NSExpression expressionForFunction:@"> now" arguments:[NSArray arrayWithObject:keyPathExpression]];

我正试图弄清楚如何编写这个函数。我尝试了其他变体,例如 SELF > now%@ > nowSELF > now()

所有这些都给了我SIGABRT

【问题讨论】:

    标签: objective-c ios nsdate nsfetchrequest


    【解决方案1】:

    1) 你需要NSPredicate

    2) 我不确定所有后端都支持now()

    3) 但是您现在可以评估并将其替换为参数:

    NSPredicate *p = [NSPredicate predicateWithFormat:@"eventDate > %@", [NSDate date]];
    [fetchRequest setPredicate:p];
    

    【讨论】:

    【解决方案2】:

    由于您在那里进行了比较,因此您没有NSExpression,而是NSPredicate

    NSPredicate *p = [NSPredicate predicateWithFormat:@"eventDate > now()"];
    [fetchRequest setPredicate:p];
    

    事实证明,如果您在 SQLite 支持的 CoreData 存储上使用此谓词,您将无法使用 now()。你可以做的是(如suggested by @Krizz):

    NSPredicate *p = [NSPredicate predicateWithFormat:@"eventDate > %@", [NSDate date]];
    

    【讨论】:

    • 感谢您的回复。我更改了代码,但现在出现了错误:*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“不支持的函数表达式 now()”
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多