我有一个包含书籍和作者的核心数据项目。在数据模型中,Authors 与 Books 是一对多的关系,Books 与 Authors 是一对一的关系。我正在尝试提取所有没有作者的书籍。无论我如何尝试,都不会返回任何结果。在我的谓词中,我也尝试过 = NIL,== nil,== NIL。任何建议,将不胜感激。
// fetch all books without authors
- (NSMutableArray *)fetchOrphanedBooks {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == nil"];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSString *sectionKey = @"name";//nil;
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext
sectionNameKeyPath:sectionKey cacheName:nil];
BOOL success = [aFetchedResultsController performFetch:nil];
NSMutableArray *orphans = nil;
// this is always 0
NSLog(@"Orphans found: %i", aFetchedResultsController.fetchedObjects.count);
if (aFetchedResultsController.fetchedObjects.count > 0)
{
orphans = [[NSMutableArray alloc] init];
for (Book *book in aFetchedResultsController.fetchedObjects)
{
if (book.author == nil)
{
[orphans addObject:book];
}
}
}
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return [orphans autorelease];
}