问题
I have objects stored in my CoreData that look something like this:
id name type 1 cat aaa 2 dog bbb 3 ape NULL
I'm fetching these objects based on the "type" property like this:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:self.entityName];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"type != %@", @"aaa"];
fetchRequest.fetchBatchSize = 100;
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES]];
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"section" cacheName:nil];
fetchedResultsController.delegate = self;
NSError *error = nil;
[fetchedResultsController performFetch:&error];
So, I'm simply trying to fetch all objects where type is not like "aaa".
The fetch request unexpectedly omits not only the objects with "aaa" types as specified in the predicate, but also the objects where the type is not set (null), resulting in the following:
id name type 2 bar bbb
Instead of what I'd expect:
id name type 2 dog bbb 3 ape NULL
The same problem happens when I use predicate format: NOT (type IN {"aaa", "bbb"})
. Which is the actual way I'll be needing this. This predicate results in no records getting fetched.
I fail to see why this could happen, because if I don't specify a predicate all objects get fetched properly. Objects with NULL types do get fetched correctly if I'd change the predicate to:
[NSPredicate predicateWithFormat:@"type = null"];
Please note; all of the above just illustrates what the problem boils down to. My actual code is more complicated and simply using the predicate format: type != "aaa" OR type = null
is something I'd like to avoid if possible.
Any help greatly appreciated!
回答1:
It's designated behavior. See here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-SW1
来源:https://stackoverflow.com/questions/37474058/coredata-fetchrequest-with-predicate-incorrectly-skips-null-values