2010-04-30 137 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