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

- (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类型

最佳答案

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

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

[fetchRequest setPredicate:yearPredicate];

关于ios - 具有许多NSSortDescriptor的NSFetchedResultsController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20551176/

10-13 03:50