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

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

问题描述

我有一个包含书籍和作者的核心数据项目.在数据模型中,作者与书籍是一对多的关系,书籍与作者是一对多的关系.我正在尝试提取所有没有作者的书籍.无论我如何尝试,都不会返回任何结果.在我的谓词中,我也试过 = 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];

}

推荐答案

尝试使用计数为零:

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

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

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