2010-04-30 108 views
8

我有一个核心数据项目,有书籍和作者。在数据模型中,作者与书籍和书籍有多对多的关系,与作者有一对一的关系。我试图拉出没有作者的所有书籍。无论我如何尝试,都不会返回任何结果。在我的谓词中,我也尝试了= NIL,== nil,== NIL。任何建议,将不胜感激。iPhone SDK核心数据:获取所有实体与零关系?

// 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

我编辑的代码,把谓语在其适当的形式,以便没有人会做,我做了同样的错误。 – TechZen 2010-04-30 19:31:57

+0

是否需要书 - >作者关系? – TechZen 2010-04-30 19:33:06

回答

24

尝试使用计数为零,而不是:

NSPrdicate *predicate = [NSPredicate predicateWithFormat:@"author == nil || [email protected] =0"]; 
1

尝试:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == nil"]; 

的 “==” 是逻辑相等。只是“=”是一项任务。

我总是犯这个错误。

编辑:

好吧,我莫名其妙地错过了在OP,他说他已经试过了。抱歉。

+5

这个符号以相同的方式工作 =,== 左边的表达式等于右边的表达式。 http://developer.apple.com/library/ios/#Documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html – Danil 2013-05-29 10:00:47