我有一个拥有图书和作者的核心数据项目。在数据模型中,作者与书籍和书籍有很多关系,与作者有1-1的关系。我正在尝试拉出所有没有作者的书籍。无论我如何尝试,都不会返回任何结果。在我的谓词中,我也试过= 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];
}
答案 0 :(得分:25)
尝试使用零计数:
NSPrdicate *predicate = [NSPredicate predicateWithFormat:@"author == nil || author.@count =0"];
答案 1 :(得分:0)
尝试:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == nil"];
“==”是逻辑上相等的。只是“=”是一项任务。
我一直都犯这个错误。
编辑:
好吧,我在OP中错过了他说他已经尝试过了。抱歉。