views:

139

answers:

2

I have a core data project that has Books and Authors. In the data model Authors has a to-many relationship to Books and Books has a 1-1 relationship with Authors. I'm trying to pull all Books that do not have an Author. No matter how I try it, no results are returned. In my predicate I've also tried = NIL, == nil, == NIL. Any suggestions would be appreciated.

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

}
A: 

Try:

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

The "==" is the logical equal. Just "=" is an assignment.

I make this mistake all the time.

Edit:

Okay, I somehow missed in the OP that he said he'd already tried that. Sorry.

TechZen
+1  A: 

Try a count of zero instead:

NSPrdicate *pred = [NSPredicate predicate with format:@"author == nil || author.@count =0"];
Marcus S. Zarra