How to configure NSPredicate to search for objects with nil attribute

I have a ManagedObject class , and one of the members of the class is NSDate . I would like to display all the objects of the class for which the date is NOT set. I tried using a predicate like this:

 NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(date = NIL)"]; 

But I still get the objects where date set. What is the correct way to create a predicate for this?

+46
objective-c nspredicate
Apr 21 '11 at 20:26
source share
4 answers

I think this is a case sensitivity case. You can use "nil" or "NULL", but not "NIL". This works fine for me:

 NSPredicate *eventWithNoEndDate = [NSPredicate predicateWithFormat:@"endDate = nil"]; 
+92
Oct 17 2018-11-21T00:
source share

Figured it out. It was not possible to do this using a predicate with a string format, so I tried a predicate with a template, and it worked. Here is the code that gave me the objects whose endDate is set to NULL:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"endDate = $DATE"]; predicate = [predicate predicateWithSubstitutionVariables: [NSDictionary dictionaryWithObject:[NSNull null] forKey: @"DATE"]]; 
+9
Apr 24 2018-11-21T00:
source share

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-SW4

the following code should work

 predicate = [NSPredicate predicateWithFormat:@"firstName = nil"]; 
+3
Mar 25 '14 at 8:29
source share

There is a very unpleasant behavior for select queries, as described by Apple:

If the object in the context has been changed, the predicate is evaluated by its changed state, and not by the current state in persistent storage. Therefore, if the object in the context has been changed in such a way that it satisfies the criteria of the select queries, the query retrieves it even if the changes were not stored in the repository and the values ​​in the repository are such that they do not meet the criteria. Conversely, if the object in the context has been changed so that it does not match the query, the query will not retrieve it, even if the version in the repository does not match.

Perhaps you will clear the date elsewhere, and the fetch request includes results in which the date is nil in memory but still set to disk (in persistent storage), and therefore, when an object causes an error, it loads the object with the installed date.

My only advice would be to coordinate access to the context of the managed entity (for example, on NSOperationQueue ) so that any updates can be stored in persistent storage before executing the select query.

0
Dec 11 '17 at 19:36
source share



All Articles