带有许多NSSortDescriptor的NSFetchedResultsController

时间:2013-12-12 18:18:49

标签: ios nsfetchedresultscontroller nssortdescriptor

在我的应用程序中我只使用一个NSSortDescriptor对实体进行排序,但现在我需要过滤4个不同属性的数据。这是当前排序的代码,结果是来自按属性'displayOrder'排序的实体的所有记录,但我需要通过其他四个属性(年,月,日,组)过滤记录,所有这些都是integer32除了字符串组

- (NSFetchedResultsController *)fetchedResultsController
{
  if (fetchedResultsController) return fetchedResultsController;

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = 
               [NSEntityDescription entityForName:@"FavoriteThing" 
                           inManagedObjectContext:managedObjectContext];

  [fetchRequest setEntity:entity];

  NSSortDescriptor *sortDescriptor = 
              [[NSSortDescriptor alloc] initWithKey:@"displayOrder" 
                                          ascending:YES];

  NSArray *sortDescriptors = [[NSArray alloc] 
                              initWithObjects:sortDescriptor, nil];  
  [fetchRequest setSortDescriptors:sortDescriptors];

  NSFetchedResultsController *aFetchedResultsController = 
              [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                                  managedObjectContext:managedObjectContext
                                                    sectionNameKeyPath:nil cacheName:@"ThingsCache"];
  aFetchedResultsController.delegate = self;
  [self setFetchedResultsController:aFetchedResultsController];

  [aFetchedResultsController release];
  [fetchRequest release];
  [sortDescriptor release];
  [sortDescriptors release];

  return fetchedResultsController;
}    

我尝试添加谓词:

NSNumber *yearSearched = 1965;
NSPredicate *yearPredicate = [NSPredicate predicateWithFormat:@"todoYear = %@", yearSearched];

[fetchRequest setPredicate:yearPredicate];

但是在运行应用程序后,行NSPredicate *yearPredicate = [NSPredicate predicateWithFormat:@"todoYear = %@", yearSearched];

上出现错误EXC_BAD_ACCESS

属性'todoYear'来自Integer32类型

1 个答案:

答案 0 :(得分:1)

您的NSNumber创建错误(您只是将指针设置为整数)。它应该是:

NSNumber *yearSearched = @1965;
NSPredicate *yearPredicate = [NSPredicate predicateWithFormat:@"todoYear = %@", yearSearched];

[fetchRequest setPredicate:yearPredicate];