如何设置NSPredicate以查找具有nil属性的对象

mez*_*ulu 51 objective-c nspredicate

我有一个ManagedObject class,而且班上的一个成员是一个NSDate.我想显示未设置日期的类的所有对象.我尝试使用这样的谓词:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(date = NIL)"];
Run Code Online (Sandbox Code Playgroud)

但我仍然得到date设置的对象.为此设置谓词的正确方法是什么?

Chr*_*lay 102

我认为这是一个区分大小写的问题.您可以使用"nil"或"NULL",但不能使用"NIL".这对我来说很好:

NSPredicate *eventWithNoEndDate = [NSPredicate predicateWithFormat:@"endDate = nil"];
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.我看到=和==在这个问题上的行为并不相同,所以最让每个人都接受 (10认同)
  • 根据 [Apple 的文档](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html) `=` 和 `==` 在谓词中是等价的 (2认同)

mez*_*ulu 10

弄清楚了.无法通过使用带有字符串格式的谓词来执行此操作,因此尝试使用模板的谓词并且它有效.这是给我的endDate设置为NULL的对象的代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"endDate = $DATE"];
predicate = [predicate predicateWithSubstitutionVariables:
                   [NSDictionary  dictionaryWithObject:[NSNull null] forKey: @"DATE"]];
Run Code Online (Sandbox Code Playgroud)