NSPredicate使用NSManagedObject的帮助方法进行过滤

时间:2011-08-03 14:44:56

标签: objective-c core-data uitableview nsfetchedresultscontroller

我有一个UITable视图,其中包含一个名为Assignment的NSManagedObjects列表。我正在使用NSPredicate来过滤列表。 我正在过滤今天和昨天应该为玩家展示的作业:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"player == %@ AND (day == %@ OR day == %@)", 
                          player, 
                          [NSNumber numberWithInt:[self todaysDayNumber]],
                          [NSNumber numberWithInt:[self yesterdaysDayNumber]]];

我需要添加额外级别的过滤。我想过滤掉只应每两周显示一次的作业。所以我将这些方法添加到Assigment:

-(BOOL)thisWeeks{
  //If this is a weekly assigment
  if ([self.weekly boolValue]) {
    return YES;
  }

  //Determine the week number
  NSCalendar *calendar = [NSCalendar currentCalendar];
  NSUInteger unitFlags = NSWeekCalendarUnit;
  NSDateComponents *dateComponents = [calendar components:unitFlags 
                                                 fromDate:[NSDate date]];
  NSUInteger week = [dateComponents week];

  //Assigned week even?
  if ([self.weekNumber intValue] % 2){
    //Current week even?
    if (week % 2) {
        return YES;
    }  
  } 
  //Assigned week odd?
  if (!week % 2) {
  //Current week odd?
    if (![self.weekNumber intValue] % 2){
      return YES;
    }
  }
//Should not be shown this week.
return NO;
}

是否可以将此帮助方法“thisWeeks”用作NSPredicate中的过滤器?

如果我“做错了”,我可以手动过滤获取的结果,但我不确定如何将结果放回NSFetchedResultsController,以便我的UITable视图可以继续使用NSFetchedResultsController。

1 个答案:

答案 0 :(得分:1)

NSPredicate 也接受块作为谓词。这是第一次检查 thisWeeks 的例子:

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bind) {
    return [self.weekly boolValue];
}];

现在你可以实现方法 - (BOOL)thisWeeksWithObject:(id)object 并写下这个:

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bind) {
    return [self thisWeeksWithObject:obj];
}];

当然,您必须将方法中的 self 更改为 object