带有谓词的 CoreData fetchRequest 错误地跳过 NULL 值

CoreData fetchRequest with predicate incorrectly skips NULL values

我的 CoreData 中存储了如下所示的对象:

id  name  type
1   cat   aaa
2   dog   bbb
3   ape   NULL

我正在基于 "type" 属性 获取这些对象,如下所示:

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];

所以,我只是想获取所有类型与 "aaa" 不同的对象。

提取请求意外地遗漏了谓词中指定的 "aaa" 类型的对象,还遗漏了未设置类型 (null) 的对象,导致以下结果:

id  name  type
2   bar   bbb

而不是我所期望的:

id  name  type
2   dog   bbb
3   ape   NULL

同样的问题发生在我使用谓词格式时:NOT (type IN {"aaa", "bbb"})。这是我需要这个的实际方式。此谓词不会获取任何记录。

我不明白为什么会发生这种情况,因为如果我不指定谓词,所有对象都会被正确获取。如果我将谓词更改为:

,则可以正确获取具有 NULL 类型的对象
[NSPredicate predicateWithFormat:@"type = null"];

请注意;以上所有只是说明问题归结为什么。我的实际代码更复杂,只是使用谓词格式:type != "aaa" OR type = null 是我想尽可能避免的。

非常感谢任何帮助!

这是指定的行为。看这里: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-SW1