iPhone SDK核心数据:获取所有与无关系的实体? [英] iPhone SDK Core Data: Fetch all entities with a nil relationship?

查看:152
本文介绍了iPhone SDK核心数据:获取所有与无关系的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个拥有图书和作者的核心数据项目。在数据模型中作者与图书有一对多的关系,图书与作者有1-1关系。我试图拉所有没有作者的书。不管我怎么尝试,没有返回结果。在我的谓词我也试过= NIL,== nil,== NIL。

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 count of zero instead:

Try using a count of zero instead:

NSPrdicate *predicate = [NSPredicate predicateWithFormat:@"author == nil || author.@count =0"];

这篇关于iPhone SDK核心数据:获取所有与无关系的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆